Reputation: 4309
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 ?
Upvotes: 7
Views: 7596
Reputation: 202346
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:
Upvotes: 4