有一个newData
数组和forkJoin
带有两种方法的rxjs运算符。我试图填充其中的数组getNewData()
以便在forkJoin订阅中使用它,但是它仍然是未定义的。getNewData()
为了在forkJoin订阅中使用newData数组,哪种方法合适?
newData = [];
forkJoin(
this.method1();
this.method2()
).subscribe({ data1, data2 }) => {
const filteredData = data1.filter(item => item.id === model.id);
this.getNewData(filteredData);
console.log(this.newData) => undefined
// wait for this.newData?
}
// Observable
getNewData(filteredData) {
return this.API('GET', `data/${filteredData.id}`).pipe(map((resp: any) => {
this.newData = resp;
}));
}
您正在尝试不鼓励使用嵌套订阅。
如果调用完全相互独立,则可以将this.API('GET', 'data')
call作为第三个参数附加到forkJoin
函数中。
import { forkJoin } from 'rxjs';
newData = [];
forkJoin(
this.method1(),
this.method2(),
this.API('GET', `data`)
).subscribe([ data1, data2, newData ]) => {
const filteredData = data1.filter(item => item.id === model.id);
this.newData = newData;
console.log(this.newData);
}
或者,如果API调用某种程度上取决于前两种方法中的数据,那么您可以使用RxJS高阶映射运算符之一,例如switchMap
。
import { forkJoin } from 'rxjs';
import { swithcMap } from 'rxjs/operators';
newData = [];
forkJoin(
this.method1(),
this.method2()
).pipe(
switchMap(([data1, data2]) => {
const filteredData = data1.filter(item => item.id === model.id);
return this.getNewData(filteredData);
})
).subscribe(newData => {
this.newData = newData;
console.log(this.newData);
}
getNewData (filteredData): Observable<any> {
return this.API('GET', `data/${filteredData.id}`).pipe(
map((resp: any) => {
this.newData = resp;
})
);
}
更新(根据OP的更新):
您希望使用forkJoin
另一个HTTP调用内部的输出。然后,您需要switchMap
如图所示进行操作。
(与问题无关)更新原始帖子中的内容时,请尝试提供这样的注释。它使您更容易理解您的意图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句