【发布时间】:2021-09-14 07:24:22
【问题描述】:
我有一个应用程序应该return menu based on given context。
以下是menuA和menuB的来源。
// example of menu derived from given source
menuA() {
return [
{
a: 'demo1',
b: 'demo2',
c: 'demo3'
},
{
e: 'demo4',
f: 'demo5',
g: 'demo6'
}
];
}
// example of menu fetched from different source eg: db
async menuB() {
const ret = [];
const h = {
a: 'demo1',
b: 'demo2',
c: 'demo3'
};
ret.push(h);
return await ret;
}
鉴于我对 rxjs 的知识和经验有限,我希望下面的 sn-p 可以接受 string 或 menuA 或 menuB 以返回 observable 的 required menu:
getMenu$(context: string) {
return forkJoin(
{
menuA: of(this.menuA()),
menuB: from(this.menuB())
}
).pipe(
mergeMap((m: any) => {
return m[context];
})
)
}
以上调用警告如下:
Argument of type 'Observable<unknown>' is not assignable to parameter of type 'OperatorFunction<{ menuA: ({ a: string; b: string; c: string; e?: undefined; f?: undefined; g?: undefined; } | { e: string; f: string; g: string; a?: undefined; b?: undefined; c?: undefined; })[]; menuB: { a: string; b: string; c: string; }[]; }, unknown>'.
Type 'Observable<unknown>' provides no match for the signature '(source: Observable<{ menuA: ({ a: string; b: string; c: string; e?: undefined; f?: undefined; g?: undefined; } | { e: string; f: string; g: string; a?: undefined; b?: undefined; c?: undefined; })[]; menuB: { a: string; b: string; c: string; }[]; }>): Observable<...>'.ts(2345)
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<any>'.ts(2684)
根据下面的评论,我还添加了使用地图替换mergeMap时的警告消息:
// modified getMenu$:
getMenu$(context: string) {
return forkJoin(
{
menuA: of(this.menuA()),
menuB: from(this.menuB())
}
).pipe(
map(m => m[context])
)
}
警告信息:
Argument of type 'Observable<unknown>' is not assignable to parameter of type 'OperatorFunction<{ menuA: ({ a: string; b: string; c: string; e?: undefined; f?: undefined; g?: undefined; } | { e: string; f: string; g: string; a?: undefined; b?: undefined; c?: undefined; })[]; menuB: { a: string; b: string; c: string; }[]; }, unknown>'.
Type 'Observable<unknown>' provides no match for the signature '(source: Observable<{ menuA: ({ a: string; b: string; c: string; e?: undefined; f?: undefined; g?: undefined; } | { e: string; f: string; g: string; a?: undefined; b?: undefined; c?: undefined; })[]; menuB: { a: string; b: string; c: string; }[]; }>): Observable<...>'.ts(2345)
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<unknown>'.ts(2684)
我正在使用angular 12 和rxjs "~6.6.0"。
【问题讨论】:
-
将
mergeMap替换为map运算符以返回正确的菜单。 -
我不确定
return await ret;应该做什么。ret是一个数组,但也许它只是一个简化的例子。 -
当我使用 map 而不是 mergeMap 时,我收到类似的警告:'Observable
' 类型的参数不可分配给'OperatorFunction 类型的参数 -
返回的 await ret 只是一个简单的 sn-p 表示异步数据源。否则,主要感兴趣的领域是开发通过字符串上下文选择从不同来源(包括 Promise)返回菜单的能力。
标签: javascript angular rxjs