Search code examples
rxjsrxjs5

compilation problem/error while using an rxjs switchmap


Hi i am getting an error in my code . I have an angular 5 formGroup and i am trying to use the pipe operation and switchMap inside.

However it give me an error. The following is my code snippet.

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

  )

).subscribe();

the error i is as below

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)

really appreciate any help thank you


Solution

  • You have to return an observable in the switchMap. switchMap switches to a new observable and you can do it conditionally based on the previous value.

    If you want to just console.log, I would use tap.

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

    ====================== Edit ========================== I assume this.generatePerformanceGraph(formValue); is a regular function and it doesn't return an observable, then you can do it in the 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);
    });