Austin Harris
Austin Harris

Reputation: 5410

Angular 5 HTTP interceptor not working

My interceptor service is adding the authorization header to my http calls, but fails to include the actual bearer token value that I pass into the interceptor service. The bearer token value that appears in chrome dev tools is just the 'not set' value, not the bearer token value. The bearer token value does show correctly when I console log it from the login component so I know is it being set, but I guess it is getting reset back to the 'not set' value at some point before it is used in the subsequent http call?

import { Component, OnInit }                            from '@angular/core';
import { Router }                                       from "@angular/router";
import { HttpClient }                                   from "@angular/common/http";
import { Response, Headers, RequestOptions }            from "@angular/http";
import { AuthInterceptor }                              from "../../services/authInterceptor.service";
import { MatSnackBar }                                  from '@angular/material';
import "rxjs/Rx";

@Component({
  selector: 'login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {    

    memberLogin: any = { 
        'emailAddress': '', 
        'password': '' 
    };

    public constructor(private http: HttpClient, private authInterceptor: AuthInterceptor, public snackBar: MatSnackBar, public router: Router) {        
    }

    public ngOnInit() { 
    }

    public login() {

        let url: string = 'http://localhost:63741/api/Account/Login';
        let body = { "Email": this.memberLogin.emailAddress, "Password": this.memberLogin.password };

        this.http.post(url, body)             
            .subscribe(
                data => {       
                    this.authInterceptor.authToken = data.toString();
                    console.log('token data in login component : ' + this.authInterceptor.authToken);  
                    this.snackBar.open('welcome back, you are now logged in', 'ok', { duration: 2200 })                    
                },
                err => {

                });

        return;
    }; 

}

import { Injectable }                                               from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest }     from '@angular/common/http';
import { Observable }                                               from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor {

    authToken: string = 'not set';

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.authToken ) });
        return next.handle(authReq);
    }
}

Upvotes: 1

Views: 9786

Answers (1)

Tom Winch
Tom Winch

Reputation: 131

The AuthInterceptor that you are injecting into LoginComponent is not the same object as the one used by the HttpClient framework (i.e. the one in the useClass for HTTP_INTERCEPTORS in AppModule).

Have the AuthInterceptor use a new injectable, say AuthService, in which you store the authToken. Inject this into both the AuthInterceptor and LoginComponent:

@Injectable()
export class AuthService {
    public authToken: string = 'not set';
}

Make sure to declare this as a provider in AppModule.

Upvotes: 1

Related Questions