Suppose I have an Angular 2 service. The createTokenfunction receives the login token from the server:
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:
- Store it in local storage (which will be executed every time, so it should be in service)
- Do some operations on it in the component (display it or something else)
To do this (as far as I understand Observables), my function createTokenmust return Observable<>in order to allow the Component, which will use it, to call its method .subscribeto perform some operations with the result.
Unfortunately, as I see from the RxJS documentation , the method .subscribedoes not returnObservable<>
, .subscribe()?