Reputation: 2034
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:
Service - Make api call to get token, set token via the token service and set isSignedIn
bool then defer control back to the calling component.
@Component({...})
export class SignIn {
private signIn:SignInModel = new SignInModel();
constructor(private auth:Auth, private router:Router) {
}
ngOnInit() {
}
signInSubmit() {
this.auth.signIn(this.signIn)
.subscribe(
() => {
this.router.navigate(['/admin']);
}
)
}
}
@Injectable()
export class Auth {
private isSignedIn:boolean = false;
constructor(private api:Api, private tokenService:TokenService) {
}
public signIn(signIn:SignInModel) {
return this.api.postSignIn(signIn)
.subscribe(
response => {
this.tokenService.set(new TokenModel(response.token));
this.isSignedIn = true;
},
error => {
console.log(error);
}
);
}
public signOut() {
}
}
Upvotes: 1
Views: 304
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