Angular 5 synchronous HTTP call

前端 未结 3 363
失恋的感觉
失恋的感觉 2021-01-04 03:34

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

3条回答
  •  日久生厌
    2021-01-04 03:58

    I upvoted the response of David above, but I think there may be a design flaw. You should actually not save (in local storage) the result in the getResult function. It's a side effect and it might be undesirable at some point and render your getResult hardly reusable in case you just want to get without save.

    Also having the this.result === 'undefined' might create problem as well if you want to refresh the data.

    So if you want to get these results in the ngOnInit, you could do it like that:

    ngOnInit() {
        if (typeof this.result === 'undefined') {
            this.getResult().then(result => {
                // save the result here
                this.result = result;
    
                // save in local storage ...
            });
        }
    }
    
    getResult(): Promise {
        return this.service.call().toPromise();
    }
    

    Note that you cannot await in ngOnInit. But now your getResult() function is reusable in many other cases.

提交回复
热议问题