rtn
rtn

Reputation: 2034

How to chain/combine Observables

Ok this has been bugging me for a while, wondering if any one could show me a good way of chaining Observables between multiple services.

In the example below in the Auth class what would be a good way of creating an Observable from the this.api.postSignIn() so the signInSubmit() can subscribe to it back in the component? It is worth noting that this.api.postSignIn() is subscribing to an Angular2 http request.

Is this a bit of an anti pattern and is there better ways of doing this?

Basically the functionality I would like to achieve is:

Upvotes: 1

Views: 304

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

I would leverage the do and catch operators instead of subscribing within the signIn method.

Here is the refactored signIn method:

public signIn(signIn:SignInModel) {
   return this.api.postSignIn(signIn)
        .do(
            response => {
                this.tokenService.set(new TokenModel(response.token));
                this.isSignedIn = true;
            })
        .catch(
            error => {
                console.log(error);
            }
        );
}

In your case, you can't subscribe on the returned object of this method since the subscribe method returns a subscription and not an observable. So you can't subscribe on it...

Upvotes: 2

Related Questions