【发布时间】:2017-11-08 04:12:41
【问题描述】:
我没有收到任何错误,并且能够使用有效令牌(我已通过 Postman 验证)从我的登录组件中设置 authToken 值。但是我没有将任何授权参数添加到我的请求标头中。
entryComponents: [
ConfirmDialogTargetComponent
],
providers: [
AuthInterceptor,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor {
authToken: string = '';
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.authToken) });
return next.handle(authReq);
}
}
【问题讨论】:
-
你试过在拦截方法中调试和设置断点吗?您使用的是 HttpClientModule 而不是 HttpModule?
-
我正在使用 HttpModule - 这是正确的吗?
-
从 app.module 导入 { HttpModule } from '@angular/http';从“@angular/common/http”导入 { HTTP_INTERCEPTORS };
-
如果您使用 Http 类而不是 HttpClient 类来发出请求,那么您混合了 API
标签: angular angular-http-interceptors angular-httpclient