2

Im tying to work with angular 2 and rxjs and i have encounter a problem.

Im trying to do a basic login: here is the code:

class LoginPage{
    ctor(private auth:AuthService) {}

    login(cred) {
        this.auth.login(cred).subscribe( res=> this.navigateToHome()
    }
}

class AuthService {
    ctor(private http:AuthHttp) {}

    login(cred){
        return this.http.post(url, cred).subscribe(res => this.onLoginSuccess())

     }
}

class AuthHttp extends Http {
   ctor (.....)

   post(...) {
     // Add some headers
      return super.post(..)
   }
}

Now first of all the wont work since the login in AuthService is now returning Subscription object and not an Observable, In addtional if take the login function and refactoring it like that:

login(cred) {
   var obs = this.http.post(url, cred)
   obs.subscribe(res=> this.onLoginSuccess())
   retrun obs
 }

This Causes the http request to invoke two times..

So my problem is: how can I know im my loginPage that the subscriber that invokes the onLoginSuccess is done?

How can i avoid the 2 time request?

1 Answer 1

3

What about share()?

If you need to subscribe on AuthService.login(), then login() must return Observable. But you need also do something on login inside AuthService, isnt it? share() let you subscribe on login inside AuthService and return Observable.

class AuthService {
    ctor(private http:AuthHttp) {}

    login(cred){
        var result = this.http.post(url, cred).share();
        result.subscribe(res => this.onLoginSuccess())
        return result;
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can please share some more details? what is the difference between this and do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.