【发布时间】:2020-08-21 20:05:47
【问题描述】:
我是 Angular 的新手,我正在尝试发出 http get 请求,并根据它的响应,我必须进行后端调用。
我在这里尝试链接 2 个异步调用,不确定这在 Angular 中是否可行/正确(使用 Angular 7 版本)。
问题陈述:在从第一个 (http) 异步调用获得响应之前进行第二次(后端)aysnc 调用。
我尝试使用 async/await 实现(理解不是正确的方法,但仍然尝试过)并在订阅第一个 http 调用时调用后端调用。两种方法都不起作用。请让我知道这里出了什么问题以及是否有更好的方法来链接 2 个异步调用。
下面是代码sn-p(简化版)
export class BasicService{
let httpUrl:string=null;
constructor(protected http: HttpClient, protected backendSvc: BackendService) {
httpUrl='/someUrl';
}
getComponentData(route: ActivatedRoute): Observable<ComponentData> {
let callName:string;
let inputPayload:string;
let routeID=route.snapshot.url[0].path;
if (routeID.Equals('Test')) {
callName='TestCall';
}
else if (routeID.Equals('Execute')) {
callName='ExecuteCall';
}
//Failure#1: Get http response back and then call backendSvc, inputPayload remains empty
//want to wait for _waitCreateInputPayload to finish execution before calling backendSvc
inputPayload = this._waitCreateInputPayload(httpUrl,callName);
//backendSvc returns an observable
return this.backendSvc.GetData(callName, inputPayload, null, this.FormFactorType);
//Failure#2: This approach also doesn't work.
this._createInputPayload(httpUrl,callName).subscribe(tempVal=>{
if(tempVal!=undefined){
return this.backendSvc.GetData(callName, tempVal, null, this.FormFactorType);
}else{
return null;
}
});
}
private async _waitCreateInputPayload(httpUrl: string, callName:string){
return await this.http.get(httpUrl, { responseType: 'text' }).subscribe(tempVal=>{
console.log('in _createInputPayload');
return tempVal;
});
}
private _createInputPayload(httpUrl: string, callName:string): string{
return this.http.get(httpUrl, { responseType: 'text' });
}
}
组件代码如下所示:
export class ChildTemplateComponent implements OnInit {
constructor(protected basicSvc: BasicService, protected route: ActivatedRoute) {}
ngOnInit() {
this.formFactorSvc = this.route.snapshot.data['formFactor'];
this.formFactorSvc.getDesignConfig(this.route);
}
ngInit() {
this.basicSvc.getComponentData(this.route).subscribe((x) => {
this.populateData(x);
});
}
populateData(data: ComponentData){
//populate the View
}
}
谢谢,
RDV
【问题讨论】:
标签: angular async-await observable httprequest subscribe