1

I have a private method which i use for authentication. Then i have another method (public) that i call in my components called login to do the actual login. I want to be able to subscribe to the login method which in reality subscribe's to the private authentication method so that i can show loading and other messages while login in being performed differently for each view. Is it possible?

Authentication method:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password}).subscribe(
        res     => this.saveJwt(res.bearerToken),
        err     => this.logError(err),
        ()      => console.log("Authentication done.")
    );
}

Login method:

login( email: string, password: string ) {
    this.logout();
    return this.userAuthenticate(email, password);
}

I want to subscribe to the login method so that i can control my loaders and error messages etc. Please help.

Hassan
  • 2,308
  • 5
  • 21
  • 31

1 Answers1

5

You can't subscribe to Subscription (returned by subscribe()). You can only subscribe to Observable.

To get an Observable use map() instead of subscribe(). Then the caller of login() can do the subscription.

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(
             `${this.baseApiUrl}/auth?format=json&provider=login`, 
             {userName: email, password: password}
           )
           .map(res => this.saveJwt(res.bearerToken));
}

For the other callabacks, if your really need them, you can use the catch and finally operators.

ytan11
  • 908
  • 8
  • 18
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is it possible to somehow make it work both ways, for instance calling `login` method activates the subscription automatically if not hooked? Like `login.subscribe()` in some cases and `login()` in some (which would default to previous method). If not then guess i might need to make two separate methods `$login` and `login` – Hassan Mar 29 '17 at 10:54
  • Difficult to say without more understanding why you want to do that but it sounds like an additional method that just calls `userAuthenticate().subscribe()` might do what you want. Perhaps http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in/36291681 might also be related. – Günter Zöchbauer Mar 29 '17 at 10:57
  • When you say use `catch` and `finally`, you mean in the `userAuthenticate` method right? – Hassan Mar 29 '17 at 11:05
  • Yes, in case you still want to handle errors and completion there, even when `subscribe()` isn't used there anymore. – Günter Zöchbauer Mar 29 '17 at 11:06
  • Basically i just want two ways to be able to login. (1) Global error and loaders are used in view. (2) I provide local error and loader containers. – Hassan Mar 29 '17 at 11:08