jos*_*hke 6 typescript angular-http angular-http-interceptors angular
我正在构建一个需要授权标头的新应用.通常我会使用与此scotch.io文章中的方法非常相似的内容.但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我试图找到一些关于如何使用它们的文档.
如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议.我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到"Angular Approved"方法.
这个答案借鉴了CodeWarrior链接的官方文档.
Angular允许您创建HttpInterceptor:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将其集成到您的应用中,如下所示:
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
要添加授权标头,您可以使用更改的标头克隆请求:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,拦截器的作用类似于链,因此您可以设置多个拦截器来执行不同的任务.
| 归档时间: |
|
| 查看次数: |
7414 次 |
| 最近记录: |