我尝试使用新的Angular 4.3
拦截器为所有请求设置授权标头,但是它没有起作用。我在拦截器intercept
方法中设置了断点,但浏览器没有命中它,所以似乎angular
忽略了我的拦截器。请帮忙解决,谢谢。
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}
]
})