我有一个角5应用程序,在这个应用程序中,我必须调用一些繁重的休息服务(通常需要几秒钟)。我需要它在应用程序的不同部分的结果,所以我想将结果存储在一个DataStorageService中。基本上,这是我想要达到的:
@Injectable()
export class DataStorageService {
private result: MyCustomObject;
constructor(private service: Service) {}
getResult(): MyCustomObject {
if (typeof this.result === 'undefined') {
// save result
}
return result;
}问题是如何等待HTTP请求完成,然后保存并返回“result”对象。我试着用承诺和可观察的方法来解决这个问题,但他们都没有成功。
发布于 2018-03-23 08:08:37
尝试使用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;
}发布于 2020-06-08 06:52:06
我推翻了上面大卫的回答,但我认为可能有一个设计缺陷。实际上,您不应该(在本地存储中)将结果保存在getResult函数中。这是一种副作用,在某一时刻它可能是不可取的,并且使您的getResult很难重用,以防您只想不保存就可以获得。
同时,如果您想刷新数据,使用this.result === 'undefined'也可能会造成问题。
因此,如果您想在ngOnInit中获得这些结果,您可以这样做:
ngOnInit() {
if (typeof this.result === 'undefined') {
this.getResult().then(result => {
// save the result here
this.result = result;
// save in local storage ...
});
}
}
getResult(): Promise<MyCustomObject> {
return this.service.call().toPromise();
}请注意,您不能在ngOnInit中等待。但是现在您的getResult()函数在许多其他情况下是可重用的。
发布于 2018-03-23 08:08:08
问题是如何等到HTTP请求完成,然后保存并返回're sult‘对象.
//服务守则:
ServiceMethod:Observabke<any>(){
if (typeof this.result === 'undefined') {
return this.service.call().map(res=>res);
}//这是组件中的代码。
componentMethod(){
return this.service.ServiceMethod()
.subscribe(response => {
this.result = response;
},
()=>//handle error,
() => // call completed { return this.result; // Subscriber});
}
return this.weeklyPlayer; // MyCustomObject (This return won't wait for http to get completed. Not sure why you want multiple returns.)
}希望这能有所帮助。
https://stackoverflow.com/questions/49444816
复制相似问题