在我的 Angular 6 应用程序中,我想在 switchMap
之前过滤到内部 Observable,如下所示:
基本上,我想做的是,如果存储选择器为我提供给定字符串的相关数据,我将使用 switchMap
中的响应来触发内部可观察对象并进行订阅。
这里的想法是,如果过滤成功,请使用 switchMap
查找过滤器响应的数据
this._store.pipe(select(getDetails)).pipe(map((details: detail[]) => {
return of(details.filter(({ tagName }) => tagName ===this.videoTagName))})
switchMap((data:detail)=>this._store.pipe(select(getVideosByID(data.contentIds[0]))))).subscribe(data=>{
console.log("Data",data)
})
上面的代码给出了以下错误:
Type 'detail' is missing the following properties from type 'Observable<detail[]>': _isScalar, source, operator, lift, and 10 more.ts(2345)
combineLatest
会有帮助吗?或者我只需要使用 switchMap
做一些事情..?
最佳答案
一些事情:
您应该以不与变量冲突的方式定义类型或类/接口(interface)。通常人们会将类型大写,例如
type Detail = ...
这样您就可以定义const detail: Detail = ...
.假设详细信息不是 Observable,则不应使用
of
在 RxJs 的“项目”参数中map
。map
的“项目”参数是一个函数,它将可观察对象发出的值作为其参数,并返回将发出的新值。如果您返回这里of
,您的 Observable 将发出一个 Observable(这通常不是您想要的)。这就是您收到错误的原因:switchMap
正下方期望通过管道传输到发出detail
的 Observable ,但它得到的是Observable<detail[]>
。如果你解决了这个问题,你将发出details
而不是detail
,虽然还不完美,但我们已经越来越接近了。如果您想过滤唯一的详细信息(而不是详细信息列表),则应使用
.find()
而不是.filter()
。过滤返回与谓词匹配的所有元素的数组(也许它只是一个只有 1 个元素的数组,但它仍然是一个数组)。查找返回第一个匹配的元素。现在我们发出detail
,因此 switchMap 内的输入将正常,并且错误将消失。您不需要链接
.pipe()
调用时,您可以将参数链接到单个管道内。这适用于前两个管道,但显然不适用于 switchMap 内的管道,因为如果将其移动到“主”管道内,detail
将不再在范围内。
完成所有这些后,您将获得以下代码,该代码应该可以工作:
this._store.pipe(
select(getDetails),
map((details: Detail[]) => details.find(
({ tagName }) => tagName === this.videoTagName
)),
switchMap((detail: Detail) => this._store.pipe(
select(getVideosByID(detail.contentIds[0])),
)),
).subscribe(data => console.log("Data", data));
关于 Angular 6 : RxJS switchMap operator is not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75093199/