【发布时间】:2019-10-03 23:08:32
【问题描述】:
我开始了一个新的 Angular 7 项目,我需要在其中调用 API 来获取结果列表。然后,如果特定结果在列表中,我选择它,如果没有,我创建它调用另一个 API 端点。所有这些东西都应该在ngOnInit() 方法中完成。
为了简化问题,我有以下代码:
const subject = new BehaviorSubject(null);
subject.next(6);
const res$ = subject.pipe(
mergeMap(() => getValues()),
tap((res) => {
const exists = res.find(x => subject.value === x) || null;
if (exists === null) {
// TODO: call the getNew() function, but I don't want nested call
} else {
// Do nothing
}
})
);
// res$ should contains [1, 2, 3, 4, 5, 6]
res$.subscribe(x => console.log(x));
function getValues() {
// Mocking the API call
return of([1, 2, 3, 4, 5]);
}
function getNew() {
// Mocking the API call
return of(6);
}
最后,res$ observable 应该包含所有数组(带有附加值),我想避免嵌套订阅。
非常感谢!
【问题讨论】:
标签: angular typescript rxjs