Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe RxJS Observable twice. Getting value of response two times

Tags:

angular

rxjs

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:

  1. Save it to local storage (which will be done every time, so it should be in service)
  2. Do some operations on it in Component (display it or whatever)

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?

like image 439
Piotrek Avatar asked Aug 21 '16 10:08

Piotrek


People also ask

Why is subject subscription called 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. );

Can you subscribe to observable multiple times?

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.

How does observable emit multiple values?

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.

What happens when you subscribe to an observable?

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.


1 Answers

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);
    });
like image 164
JB Nizet Avatar answered Sep 22 '22 09:09

JB Nizet