[英]Combining multiple Http streams with RxJS Observables in Angular
我试图使以下流与map和flatMap一起工作,但是它做了它应该做的事情,但是代码不是最佳的,例如,我第二次使用flatMap时,我从未读取过它的响应值,但是我只是不这样做不知道如何继续执行流程,如果删除流程,则会出现错误
类型'Observable'的参数不能分配给类型'(outerValue:any,innerValue:void,externalIndex:number,innerIndex:number)=> any'的参数
那么我该如何做得更好呢?
person;
facility;
apiUrl1: string = 'http://localhost:3000/person/?';
apiUrl2: string = 'http://localhost:3000/facility/?';
apiUrl3: string = 'http://localhost:3000/exposure/?';
constructor(private http: HttpClient) { }
getData(arg): Observable<any> {
return this.http.get(this.apiUrl1 + arg.data)
.map((response: any) =>
this.person = response
)
.flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1)
.map((response: any) => {
this.facility = response
})
.flatMap((response: any) => this.http.get(this.apiUrl3 + this.person.val2)
.map((response: any) => response.val5 * this.facility.val3)))
}
}
如果您打算使用变量this.person
, this.facility
和this.exposure
只是为了“保留”这些值,以便您可以重用先前的http调用的结果,则无需这样做。 借助.forkJoin
和数组解构 ,您可以消除它们。
这是一个更简短,简洁易读的代码:
getData(arg): Observable<any> {
return this.http.get(this.apiUrl1 + arg.data)
.flatMap((person: any) => Observable.forkJoin([...this.http.get(this.apiUrl2 + person.val1), this.http.get(this.apiUrl3 + person.val2)]))
.map(([facility, exposure]) => exposure.val5 * facility.val3)
}
P / S:给变量取适当的名称(而不是仅仅将它们命名为response
)有助于吨
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.