Rxjs 6过滤器运算符是否应使用map运算符的返回值?

时间:2019-05-13 16:31:26

标签: angular rxjs6

我具有以下功能:

原始功能

public FindCertType(CertTypeID: string) : Observable<ICertType> {
    console.log("... FindCertType in Model-tools.service called ...");
    return this.GetCertTypes()
      .pipe(
        map((CertTypeMap: IResponseObject<ICertType>) => {
          return CertTypeMap.Array
        }),
        filter((CertType: ICertType ) => CertType.Id === CertTypeID)[0]
      )
  }

此代码导致以下错误:

控制台错误

... ShowCertType called ...                           new-bcaba.component.ts:27 
... GetCertType in Certification Component called ... certification.component.ts:49
... FindCertType in Model-tools.service called ...                  model-tools.service.ts:53
... GetCertTypes in Model-tools.service called ...                  model-tools.service.ts:48

ERROR TypeError: fn is not a function                  NewBcabaComponent.html:3
    at pipe.js:18
    at Array.reduce (<anonymous>)
    at piped (pipe.js:18)
    at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.pipe (Observable.js:91)
    at ModelToolsService.push../src/app/_services/model-tools.service.ts.ModelToolsService.FindCertType (model-tools.service.ts:55)
    at NewBcabaComponent.push../src/app/certification/certification.component.ts.CertificationComponent.GetCertType (certification.component.ts:50)
    at NewBcabaComponent.get [as BaseCertType$] (certification.component.ts:54)
    at NewBcabaComponent.push../src/app/certification/application/new-bcaba/new-bcaba.component.ts.NewBcabaComponent.ShowCertType (new-bcaba.component.ts:28)
    at NewBcabaComponent.get [as ParentCertType$] (new-bcaba.component.ts:37)
    at Object.eval [as updateDirectives] (NewBcabaComponent.html:3)

当我修改函数以使过滤器与地图内联时,错误消失了,它开始按我的预期工作。

修改功能

public FindCertType(CertTypeID: string) : Observable<ICertType> {
    console.log("... FindCertType in Model-tools.service called ...");
    return this.GetCertTypes()
      .pipe(
        map((CertTypeMap: IResponseObject<ICertType>) => {
          return CertTypeMap.Array.filter(CertType => CertType.Id === CertTypeID)[0];
        })
      )
  }

虽然通过修改解决了我的问题,但我不明白为什么可以这样做,但第一个版本却无法解决。我从'rxjs / operators'导入了原始代码的“ filter”和“ map”运算符,并且据我所知,管道内的运算符应在从前一个运算符返回的observable上工作,因此filter应该在map的返回上起作用。谁能解释为什么这行不通?

0 个答案:

没有答案