Angular 7 HTTP Interceptor не работает - PullRequest
1 голос
/ 13 марта 2019

Я новичок в Angular и пытаюсь реализовать вызов API, который отправляет токен в заголовке для всех API, поэтому я использую Interceptor.

Я не могу установить заголовок в запросе.

jwt.interceptor.ts

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

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let currentUser = localStorage.getItem('useremail')
        let currentUserToken = localStorage.getItem('token')
        if (currentUser && currentUserToken) {
            request = request.clone({
                setHeaders: {
                    'Authorization': `${currentUserToken}`
                }
            });
        }
        // console.log("Request", request)
        return next.handle(request);
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppUserListingComponent } from './app-user-listing/app-user-listing.component';
import { JwtInterceptor } from './jwt.interceptor';

@NgModule({
  providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true } ],
  bootstrap: [AppComponent]
})
export class AppModule { }

пользовательский listing.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UserListingService {
  apiUrl = "URL";
  constructor(
    private http: HttpClient
  ) { }

  fetchAllUsers() {
    return this.http.get(`${this.apiUrl}/fetchAdminsUsers`)
  }

}

По какой причине мой код не работает?

Заранее спасибо

Ответы [ 3 ]

0 голосов
/ 23 мая 2019

Authorization - это специальный заголовок, вам нужно добавить withCredentials: true к запросу, чтобы добавить его.

        request = request.clone({
            setHeaders: {
                'Authorization': `${currentUserToken}`
            },
            withCredentials: true
        });
0 голосов
/ 19 июля 2019

Добавить imports: [BrowserModule, HttpClientModule] в @NgModule.

0 голосов
/ 16 мая 2019

попробуйте использовать экземпляр как показано ниже.

return next.handle(request).pipe(
            tap(
                event => {
                    if(event instanceof HttpResponse){
                        //api call success
                         console.log('success in calling API : ', event);
                    }
                },
                error => {
                    if(event instanceof HttpResponse){
                        //api call error
                        console.log('error in calling API : ', event);
                    }
                }
            )
        )
...