How to relate observable rxjs

I am coming from Angular1, and, as a promise of chaining, 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 call this method: -

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

As I mentioned as comments on the above code, the subscription is not called in the caller's class.

Any suggestion on how to do this?

+7
angular rxjs
source share
1 answer

In fact, you are returning a subscribe method object. This is a subscription, not an observable. Thus, you cannot subscribe (again) to the returned object.

Observables allows you to build a chain of data streams based on observed operators. It depends on what you want to do.

If you just start something or set a service property from your service, you can use the do and catch to handle errors:

 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); }); } 

Remember to include these operators, as they are not included out of the box in Rxjs:

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

or globally (all operators):

 import 'rxjs/Rx'; 

See related questions:

+4
source share

All Articles