Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain rxjs observable

Tags:

angular

rxjs

I am coming from Angular1, and like chaining promise, I want to have similar behavior.

I have a method in someclass:-

{.........
      doLogin (username, password) {
            .......
            .......
            return this.http.get(api).subscribe(
                    data => {.....}, //enters here
                    err => {.....}
        }

Then I am calling this method :-

 someclass.doLogin(username, password).subscribe(
           data => { }, //Not getting called
            err => { }
 }

As I mentioned as comments on the above code, the subscribe is not getting called in the caller class.

Any suggestion about how to do this ?

like image 742
VISHAL DAGA Avatar asked Mar 29 '16 08:03

VISHAL DAGA


People also ask

How do you call one observable after another?

Make a single observable out of the several ones that need to be executed in parallel (i.e. the many deletions), using forkJoin. Use switchMap to execute one observable after another.

What is Pipeable operators in RxJS?

A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified. A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output.

How do I run observable?

To execute the observable you have created and begin receiving notifications, you call its subscribe() method, passing an observer. This is a JavaScript object that defines the handlers for the notifications you receive.


1 Answers

In fact, you return the object of the subscribe method. It's a subscription and not an observable. So you won't be able to subscribe (again) to the returned object.

Observables allows to build data flow chain based on observable operators. It depends on what you want to do.

If you simply trigger something or set a service property from your service, you could use the do operator and the catch one for error handling:

doLogin (username, password) {
  .......
  .......
  return this.http.get(api).do(data => {
    .....
    // Call something imperatively
  })
  .catch(err => {
    .....
    // Eventually if you want to throw the original error
    // return Observable.throw(err);
  });
}

Don't forget to include these operators since they aren't included out of the box by Rxjs:

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

or globally (all operators):

import 'rxjs/Rx';

See related questions:

  • Angular 2, best practice to load data from a server one time and share results to components
  • Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]
like image 86
Thierry Templier Avatar answered Sep 28 '22 19:09

Thierry Templier