user3345721
user3345721

Reputation: 85

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!

Upvotes: 1

Views: 1135

Answers (2)

Marko
Marko

Reputation: 179

You can also do it without constants. For example if you want to declare variable, then assign some observable to this variable and then pipe this variable and use it as reference you can do it like this:

let action$;
switch(someVar) {
   case case1:
      action$ = someObservable;
      break;
   defualt:
      action$ = someObservable2;
      break;
}
action$ = action$.pipe(someRxjsoperator);

In this case you will assign newly create observable by pipe to declared variable.

Upvotes: 0

Gunnar B.
Gunnar B.

Reputation: 2989

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.

Upvotes: 1

Related Questions