Angular 5同步HTTP调用

asz*_*ien 12 http promise observable angular

我有一个Angular 5应用程序,我必须调用一些繁重的REST服务(通常需要几秒钟).我需要在应用程序的不同部分使用它的结果,所以我想将结果存储在DataStorageService中.基本上,这是我想实现的:

@Injectable()
export class DataStorageService {

private result: MyCustomObject;

constructor(private service: Service) {}

getResult(): MyCustomObject {
    if (typeof this.result === 'undefined') {
        // save result
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

问题是我如何等待HTTP请求完成,然后保存并返回'result'对象.我试图用Promise和Observable来解决它,但是没有一个能正常工作.

  1. 观察到:

    if (typeof this.result === 'undefined') {
        this.service.call()
            .subscribe(response => this.result = response);
    }
    return this.result;  // wait for save and return MyCustomObject
    
    Run Code Online (Sandbox Code Playgroud)
  2. 诺言:

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

Dav*_*vid 17

尝试使用 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 方法签名不应该是:async getResult():Promise <MyCustomObject>? (7认同)