Subscribe RxJS Observed twice. Getting the response value twice

Suppose I have an Angular 2 service. The createTokenfunction receives the login token from the 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:

  • 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()?

+4
1

do():

, Observable, .

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

Source: https://habr.com/ru/post/1651931/


All Articles