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
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.