Angular 5 synchronous HTTP call

旧巷老猫 提交于 2020-02-01 00:35:05

问题


I have an Angular 5 application in which I have to call some heavy REST service (usually takes some seconds). I need its result in different part of application, so I would like to store the result in a DataStorageService. Basically, this is I would like to achieve:

@Injectable()
export class DataStorageService {

private result: MyCustomObject;

constructor(private service: Service) {}

getResult(): MyCustomObject {
    if (typeof this.result === 'undefined') {
        // save result
    }
    return result;
}

The question is how I can wait until HTTP request is finished and then save and return the 'result' object. I tried to solve it using Promise and Observable as well, but none of them worked fine.

  1. Observable:

    if (typeof this.result === 'undefined') {
        this.service.call()
            .subscribe(response => this.result = response);
    }
    return this.result;  // wait for save and return MyCustomObject
    
  2. Promise:

    if (typeof this.result === 'undefined') {
        this.service.call()
            .toPromise()
            .then(response => this.result = response);
    }
    return this.result;  // wait for save and return MyCustomObject
    

回答1:


Try using await/async

async getResult(): Promise<MyCustomObject> {
    if (typeof this.result === 'undefined') 
    {
        // save result
        this.result = await this.service.call()
        .toPromise()
        .then(resp =>resp as MyCustomObject);//Do you own cast here

    }
    return this.result;
}



回答2:


The question is how I can wait until HTTP request is finished and then save and return the 're sult' object.

// Code in service:

ServiceMethod:Observabke<any>(){
     if (typeof this.result === 'undefined') {
                return this.service.call().map(res=>res);
}

// This is code in component.

 componentMethod(){


        return this.service.ServiceMethod()
            .subscribe(response => {
                this.result = response;
               },
               ()=>//handle error,
               () => // call completed { return this.result;  // Subscriber});
    }
    return this.weeklyPlayer;  // MyCustomObject (This return won't wait for http to get completed. Not sure why you want multiple returns.)

    }

Hope this helps.



来源:https://stackoverflow.com/questions/49444816/angular-5-synchronous-http-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!