Md Alamin
Md Alamin

Reputation: 1462

Angular HttpInterceptor does not work with the first request after login

I spend 2 days with this problem, I could not find any solution.

I am facing a problem with angular HTTP interceptor in an Ionic 4 project.

After login success, the router navigates to the home page and call some API with a token.

When login succeeds, I store the token to the localStorage and use this token in HTTP interceptor, In the home page the first time, the token was not set into authorization header.

If I refresh the application, then it works fine, Here I attached my code snippet below.

HTTP INTERCEPTOR:

    intercept(httpReq: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (localStorage.getItem('tokenKey')) {
            const token = localStorage.getItem('tokenKey');
            const req = httpReq.clone({
                setHeaders: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                }
            });
            return next.handle(req);
        } else {
            const req = httpReq.clone({
                headers: httpReq.headers.set('Content-Type', 'application/json'),
            });
            return next.handle(req);
        }
}

Here Is my login component code

 login() {
    this.authService.login(this.user)
        .then((data: any) => {
            this.events.publish('user:created', data.profile);
            this.events.publish('token:created', data.token);
            if (data.token) {
             this.router.navigate(['home']);
          }
      }).catch(error => {
         this.presentAlert(error);
      });
}

Here is login service code:

login(user) {
return new Promise((resolve, reject) => {
    this.http.post(ApiEndPoint + 'signin/index', user).subscribe((data: any) => {
        localStorage.setItem('tokenKey', data.data.token);
        this.authState.next(true);
        resolve(data.data);
    }, err => {
        reject(err);
    });
});}

Upvotes: 4

Views: 1612

Answers (1)

MB_18
MB_18

Reputation: 2311

In app.module.ts, add your interceptor to the providers.

For example, if the interceptor name is JwTokenInterceptor. In app.module.ts, you should add it to the providers as below:

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwTokenInterceptor, multi: true }
  ],

For more information see intercepting-requests-and-responses.

Upvotes: 0

Related Questions