How do I get the Header of a Sponse with Angular 2+?

Asked

Viewed 742 times

1

How do I get a response header with Angular 2+? In my case, I’m using version 6.

I would like to take this Authorization data to be stored in the Browser Localsession.

Response Header

I am using the following method to perform the request:

public login(email: string, password: string): Observable<User> {
        return this.http.post<User>(this.url, { username: email, password: password })
            .do(user => {
                this.user = user;

            });
    }

In the class of my component, try to rescue through the Httpheaderresponse Method, but without success!

public login(): void {
        this.signinService.login(this.loginForm.value.email, this.loginForm.value.password
        ).subscribe(
            (user: User) => {
                this.notificationService.notify(`Usuário logado com sucesso`);
                let header: HttpHeaderResponse = new HttpHeaderResponse();
                console.log(header);
                localStorage.setItem('token', 'Aqui vai o Token');
            },
            (response: HttpErrorResponse) => this.notificationService.notify(response.error.message),
            () => {
                this.router.navigate([atob(this.navigateTo)]);
            });
    }

I thank the community for their cooperation!

  • 1

    Edit the question and enter the code you use to make the request

  • Added Pedro! Thank you for the tip!

1 answer

0

You could do something like:

  public login(email: string, password: string): Observable<User> {
      return this.http
                 .post<User>(this.url, { username: email, password: password })
                  .pipe(
                    tap( resp => {
                      const token = resp.headers.get('X-Access-Token');
                      localStorage.setItem('token', token);
                      this.user = user;
                    }));
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.