【问题标题】:rxjs pipes: Argument of type Observable not assignable to parameterrxjs管道:Observable类型的参数不可分配给参数
【发布时间】:2018-09-19 20:23:57
【问题描述】:

我是 rxjs 和管道的新手 - 并试图理解为什么我会收到此打字稿错误:“Observable 类型的参数不能分配给参数 OperatorFunction”。有人可以向我解释一下吗?

意图是请求“Hello”,但在数据通过管道传输时将数据替换为“Bye”。

  ngOnInit() {
    this.getHello()
      .pipe(this.getBye())
      .subscribe(data => console.log(data))
  }
  getHello() {
    return of("Hello")
  }
  getBye() {
    return of ("Bye")
  }
}

【问题讨论】:

  • 你对.pipe(this.getBye())这行有什么期望?看起来不合逻辑,这也是错误的根源
  • this.getHello().pipe(_ => this.getBye())
  • 其中一个答案解决了您的问题吗?

标签: angular rxjs6


【解决方案1】:

使用 map 作为 Pipeable Operator:

this.getHello()
  .pipe(map((data) => { return this.getBye() }))
  .subscribe(data => {
    console.log(data);
  });
getHello() {
  return of("Hello");
}
getBye() {
  return of("Bye");
}

详细检查可管道操作符的链接: https://angular.io/guide/rx-library https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44

【讨论】:

    【解决方案2】:

    管道方法接收到一个 OperatorFunction,但你给它的是你的 getBye() 方法,它返回一个 Observable。您必须传递一个 OperatorFunction,例如“map”:

    ngOnInit() {
      this.getHello()
        .pipe(map(_ => this.getBye()))
        .subscribe(data => console.log(data));
    }
    
    getHello(): Observable<string> {
      return of('Hello');
    }
    
    getBye(): string {
      return 'Bye';
    }
    

    【讨论】:

      【解决方案3】:

      当您创建自己的运算符时,您必须将函数包装在函数中。当一个新事件被设置到流上时,内部函数被调用。同时,您可以访问流本身 (sourceStream)。

      查看 Stackblitz 以获取工作示例。

       ngOnInit() {
            this.getHello()
                .pipe(this.getBye())
                .subscribe(data => console.log(data))
            }
      
            getHello() {
              return of("Hello")
            }
      
            getBye() {
              return (sourceSteam: any) => of("Bye")
            }
          }
      

      https://stackblitz.com/edit/ng-stackoverflow-52413693?file=index.ts

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 2020-11-12
        • 2020-04-17
        • 2019-06-24
        • 2021-06-14
        相关资源
        最近更新 更多