2

I'm starting to work with Angular and I have a pretty simple question.

I'm using this starter project that I created via the ngx-rocket tool, and I'm trying to implement the authentication using my webapi. I'm talking about this service (see original code).

As Http module I'm using the new one (import { HttpClient } from '@angular/common/http';). and I changed the login method of the service above to this:

  login(context: LoginContext): Observable<Credentials> {

    return  this._http.post<Credentials>("/api/account/login", 
      {Email : context.username,Password:context.password});        
  }

The http request happens and returns successfully. My problem: as you can see I should also set the credentials using this.setCredentials(data, context.remember);. What is confusing to me is how to return the observable and set the credentials in the same method? I tried keeping the returned observable in a variable, subscribing to it, setting the data and then return but it returns before setting the data (I know it's async).

This is what is confusing to me, it's pretty basic for Angular but still confusing to me. How can I change this method to give the proper return and also set the credentials?

Thanks for any help

0

2 Answers 2

4

Try using pipe

login(context: LoginContext): Observable<Credentials> {
    return this._http.post<Credentials>("/api/account/login", {Email : context.username,Password:context.password})
                .pipe(
                    tap(data => {
                        this.setCredentials(data, context.remember);
                    })
                );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! TS is giving me: cannot find name 'tap'. What should I import to have it?
import { tap } from 'rxjs/operators';
2

You can use the lettable tap (formerly do) operator and still return the observable.

import { tap } from 'rxjs/operators/tap';

login(context: LoginContext): Observable<Credentials> {
    return this._http.post<Credentials>("/api/account/login", {Email : context.username,Password:context.password})
        .pipe(do((response) => {
          // this.setCredentials(data, context.remember);
        })
    );
}

The operation is commented out because I am not sure what you are getting back or wanting to pass.

If you wanted to return something different based on the actions of setCredentials then use map instead and return something from the method.

Comments

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.