角度:我必須將 [access_token_value] 發送給訪問服務器的每個函式。我可以在全球范圍內進行嗎?
我的意思是我不想為每個函式添加它,而是寫一次
我可以做嗎?
謝謝!!
uj5u.com熱心網友回復:
您需要使用攔截器。在 Angular 官方檔案中閱讀它們。.
這是我附加的一個示例,可幫助您了解如何創建一個并將令牌傳遞給它。
import {
HttpEvent,
HttpHandler,
HttpHeaders,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('access_token') // <--- stored token to be passed to interceptor request headers
if (token) {
const authRequest = req.clone({
setHeaders: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`, // <---- your token goes here
},
})
return next.handle(authRequest)
} else {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
})
const cloned = req.clone({
headers,
})
return next.handle(cloned)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488420.html
