【问题标题】:compilation problem/error while using an rxjs switchmap使用 rxjs switchmap 时的编译问题/错误
【发布时间】:2020-06-25 15:23:35
【问题描述】:

您好,我的代码出现错误。我有一个 Angular 5 formGroup,我正在尝试在里面使用管道操作和 switchMap。

但是它给了我一个错误。以下是我的代码sn-p。

this.formGroup.valueChanges.pipe(
  switchMap(
      (formValue) => {
        console.log(formValue);
      }

  )

).subscribe();

错误i如下

Argument of type '(formValue: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.ts(2345)

非常感谢任何帮助 谢谢你

【问题讨论】:

    标签: rxjs rxjs5


    【解决方案1】:

    您必须在switchMap 中返回observableswitchMap 切换到新的 observable,您可以根据之前的值有条件地进行操作。

    如果你只想console.log,我会使用tap

    this.formGroup.valueChanges.pipe(
      tap(
          (formValue) => {
            console.log(formValue);
          }
    
      ),
    
    ).subscribe();
    

    =======================编辑======================== == 我假设this.generatePerformanceGraph(formValue); 是一个常规函数并且它不返回可观察对象,那么您可以在subscribe 中执行此操作。

    this.formGroup.valueChanges.pipe(
      tap( // you can remove this tap, it is just for logging
          (formValue) => {
            console.log(formValue);
          }
    
      ),
    
    ).subscribe(formValue => {
      this.generatePerformanceGraph(formValue);
    });
    

    【讨论】:

    • 我想要实现的是多次更改表单值并使用 swtichmap 获取最后发出的 observable 并调用函数。
    • this.formGroup.valueChanges.subscribe(formValue => { if(this.formGroup.valid) { this.generatePerformanceGraph(formValue); } }); / 这是我想与 switchMap 一起使用的代码
    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多