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 ?
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With