问题
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
回答1:
Try using 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;
}
回答2:
The question is how I can wait until HTTP request is finished and then save and return the 're sult' object.
// Code in service:
ServiceMethod:Observabke<any>(){
if (typeof this.result === 'undefined') {
return this.service.call().map(res=>res);
}
// This is code in component.
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.)
}
Hope this helps.
来源:https://stackoverflow.com/questions/49444816/angular-5-synchronous-http-call