I try to use new Angular 4.3
interceptors for setting authorithation header for all requests. However, it is not working. I set breakpoint into the interceptors intercept
method and browser did not hit it, so it seems like angular
just ignores my interceptor. Please help me, thanks in advance.
user.service.ts:
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";
import {Http} from "@angular/http";
@Injectable()
export class UserService {
constructor(public http: Http) {
}
public getContacts(): Observable<any[]> {
return this.http.get('/users/contacts').map(contacts => contacts.json());
}
}
token.interceptor.ts
import {Injectable} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from "./shared/auth.service";
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
app.module.ts:
@NgModule({
...
providers: [
...
{provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
]
})
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…