Key
到每條 API 的Request Header
headersConfig['token']
可以在外層使用 if 判別是 去判別 是否添加該 key 進物件中
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpEvent, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class ApiHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headersConfig = {
'api-version': '1',
};
headersConfig['token'] = 'youarecoder';
const request = req.clone({ setHeaders: headersConfig });
return next.handle(request);
}
}
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ApiHeaderInterceptor} from './interceptors';
/**
* http攔截器
*/
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: ApiHeaderInterceptor, multi: true },
];
@NgModule({
providers: [
httpInterceptorProviders,
]
})
export class CoreModule { }