Suppose I have an Angular 2 Service. createToken
function gets log in token from server:
//ANGULAR 2 SERVICE:
//login to application
createToken(email: string, password: string) {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let data = 'username=' + email + '&password=' + password + '&grant_type=password';
this.http.post(this.loginURL, data, { headers: headers })
.map(response => response.json())
.subscribe(
response => {
localStorage.setItem(this.storageTokenKey, response.access_token);
console.log("Token: " + response.access_token);
},
error => {
console.log(error.text());
});
}
I need to do two things with my token:
In order to do this (as far as I understand Observables), my createToken
function has to return Observable<>
to allow Component that will use it to call its .subscribe
method to do some operations on result.
Unfortunately, as I see from RxJS documentation, .subscribe
method doesn't return Observable<>
What should I do then to be able to call .subscribe()
method twice?
The most common reason for this is that you have called subscribe() multiple times. Every time it is called it adds a new message listener, even if that same listener is already registered for that event; when a message is received, every registered listener will be called with it. );
It turns out that as the Observable is just a definition, let's remember that in a sense its something close to a function declaration, if we subscribe to it multiple times this means that each time a new HTTP request will be issued, one for each subscription.
Observables can emit multiple valuesAn Observable will emit events where a defined callback executes for each event. If you want to handle a single event, use a Promise. If you want to stream multiple events from the same API, use Observables.
SubscribinglinkAn Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
You can use the do() operator:
Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source.
return this.http.post(this.loginURL, data, { headers: headers })
.map(response => response.json())
.do(response => {
localStorage.setItem(this.storageTokenKey, response.access_token);
console.log("Token: " + response.access_token);
});
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