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