Search code examples
angulartypescriptrxjspipeangular2-observables

rxjs pipe to observable does not raise when bind it to the observable reference


Can someone explain me why does this typescript code work, and - map and tap are raised:

var request = this.http.get("https://jsonplaceholder.typicode.com/todos/1")
  .pipe(
    map(x => {
      console.log(map);
      //this will be raised
    }),
    tap((x: any) => {
      console.log(tap);
      //this will be raised
    }
    ));
request.subscribe((x) => alert(x));

While in this code:

var request = this.http.get("https://jsonplaceholder.typicode.com/todos/1");
request.pipe(
  map(x => {
    console.log(map);
    //this will not be raised
  }),
  tap((x: any) => {
     console.log(tap);
    //this will not be raised
  }
  ));
request.subscribe((x) => alert(x));

map and tap are not raised. Why are they behave differently?

And if this is the expected behavior- What is the right way to separate the request creating, and the pipe to a different location, for example - one method creates the request, second binds it to the pipe, and third raises it by calling the 'subscribe'.
Thanks!


Solution

  • Essentially you need something like

    const request = this.http.get("https://jsonplaceholder.typicode.com/todos/1");
    
    const piped = request.pipe(
      map(x => {
        console.log(map);
      }),
      tap((x: any) => {
         console.log(tap);
      }
      ));
    
    const subscription = piped.subscribe((x) => alert(x));
    

    Note: Avoid var, use const/let instead, they are block-scoped (which is what you want most of the time) while var is not.