Anguar 使用interceptor攔截器設定請求頭傳入jwt token
阿新 • • 發佈:2018-11-03
1.建立http-interceptors.ts檔案
import { Injectable } from "@angular/core"; import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse, HttpHeaderResponse, HttpResponse, HttpEvent } from "@angular/common/http"; import { Observable } from "rxjs"; import { finalize, tap } from "rxjs/operators"; import { HttpService } from "../http-service/http.service"; import { LoadingService } from "../loading/loading.service"; /** Pass untouched request through to the next request handler. */ @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor( private httpService: HttpService, private loadingService: LoadingService ) {} intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { const authToken = this.httpService.getAuthorizationToken(); const authReq = req.clone({ headers: req.headers.set("Authorization", authToken), url: req.url.replace(req.url, this.httpService.reqUrl + req.url) }); return next.handle(authReq).pipe( tap( event => { this.loadingService.loading(true); if (event instanceof HttpResponse) { console.log("success"); } }, error => { console.log("failed"); } ), finalize(() => {//請求完成(成功或失敗都執行) this.loadingService.loading(false); }) ); } }
2.在app.module.ts中新增以下程式碼:
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
@NgModule({
providers: [
HttpService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
3.在元件中使用:
import { Component, OnInit, Input } from "@angular/core"; import { HttpClient } from "@angular/common/http"; @Component({ selector: "app-table", templateUrl: "./table.component.html", styleUrls: ["./table.component.css"] }) export class TableComponent implements OnInit { constructor(private http: HttpClient) {} ngOnInit() { this.getTableData(); } getTableData() { this.http.get("/api/table").subscribe(res => { console.log(res); }); } }