我寫了一個角(4.3.6)HttpInterceptor來添加一些標題字段,但如果我在調試器中檢查它們,標題不會更新。任何想法?Angular HttpInterceptor不會更改標題
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('AuthInterceptor at work');
const contentTypeReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
const token = localStorage.getItem('token');
if (token) {
const authReq = contentTypeReq.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(authReq);
}
// Pass on the cloned request instead of the original request.
return next.handle(contentTypeReq);
}
}
設置內容類型是沒用的。 Angular爲你做到了這一點。你使用調試器運行你的代碼嗎?或者只是添加console.log()來檢查令牌是否已設置? –
是的 - 我在調試器中運行它,看到它的beeing叫。但標題不更新。請參閱https://angular.io/guide/http#setting-new-headers – netshark1000