我有一个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来解决它,但是没有一个能正常工作.
观察到:
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)诺言:
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)