[英]How to call a SERVICE inside a Merge Scan when using the Reactive Approach RXJS in Angular
I am trying to use the reactive approach in my angular app and I am having trouble calling a service inside a scan.我正在尝试在我的 Angular 应用程序中使用反应式方法,但我无法在扫描中调用服务。 How do I do this?我该怎么做呢? It seems the service returns an observable - how do I deal with this?似乎服务返回了一个可观察的 - 我该如何处理? Here is the error that I see: Type 'Observable' is not assignable to type 'SomeItemModel'.这是我看到的错误:类型“Observable”不可分配给类型“SomeItemModel”。
itemsWithAdditions$ = merge(this.items$, this.saveItemAction$).pipe(
scan((acc, value) => {
//Check if an array
if (value instanceof Array) {
return this.someService.someMethod(res).pipe(map(res => {
value.forEach(item => {
item.price = res.find(x => x.id === item.id).map(x => x.price);
})
}))
}
// Otherwise, add that value to the array
else {
acc.push(value);
return acc;
}
}, [] as SomeItemModel[] // this is the initial value for the array
)
); );
I your case, you need to use mergeScan
if you want to return an observable in a scan
.在你的情况下,如果你想在scan
中返回一个 observable,你需要使用mergeScan
。 This means, any returned value must be an observable :这意味着,任何返回值都必须是可观察的:
itemsWithAdditions$ = merge(this.items$, this.saveItemAction$).pipe(
mergeScan(
(acc, value) => {
if (value instanceof Array) {
return this.someService.someMethod(res).pipe( // observable here
map((res) => {
// don't forget to return a value here
value.forEach((item) => {
item.price = res
.find((x) => x.id === item.id)
.map((x) => x.price);
});
})
);
}
else {
acc.push(value);
return of(acc); // observable here
}
},
[] as SomeItemModel[]
)
);
NB: Don't forget to return a value in a map()
.注意:不要忘记在map()
中返回一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.