相关疑难解决方法(0)

Angular 5同步HTTP调用

我有一个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)

http promise observable angular

12
推荐指数
1
解决办法
2万
查看次数

标签 统计

angular ×1

http ×1

observable ×1

promise ×1