Angular 5同步HTTP调用 [英] Angular 5 synchronous HTTP call

查看:63
本文介绍了Angular 5同步HTTP调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

问题是如何等待HTTP请求完成,然后保存并返回结果"对象.我也尝试使用Promise和Observable解决该问题,但是它们都无法正常工作.

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. 可观察的:

  1. Observable:

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

  • 承诺:

  • Promise:

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

  • 推荐答案

    尝试使用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;
    }
    

    这篇关于Angular 5同步HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆