Tiêm AuthService đến constructor của Interceptor được đem lại cho tôi lỗi này:
Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./[email protected]:-1
Vì vậy, thay vì tiêm nó vào constructor, tôi sử dụng Injector
của @angular/core
và nó làm việc tốt. Tôi đang lưu trữ mã thông báo trong localStorage
và sử dụng auth cơ bản. Tôi cần phải thiết lập
Authorization: 'Bearer token_string'
Dưới đây là cách tôi đã thực hiện:
token.interceptor.ts
import {Injectable, Injector} from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private injector: Injector) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthService);
if (auth.getToken()) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${auth.getToken()}`
}
});
}
return next.handle(request);
}
}
getToken chức năng trong AuthService
Tại đây bạn có thể triển khai toàn bộ logic để lấy tiêu đề hoặc chỉ mã thông báo. Ở đây trong trường hợp của tôi, tôi chỉ gọi điều này để lấy chuỗi mã thông báo JWT.
/**
* Get jwt token
* @returns {string}
*/
getToken(): string {
return localStorage.getItem('token');
}
app.module.ts
nhập các TokenInterceptor
import {TokenInterceptor} from './pathToTheFile/token.interceptor';
thêm dòng sau dưới @NgModule
trong providers:
mảng.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
//, other providers
]
http://blog.ninja-squad.com/2017/07/17/http-client-module/ này có vẻ hữu ích – john
Bạn có thể kiểm tra https://github.com/auth0/angular2-jwt /tree/v1.0 1.x nhánh làm ví dụ. – estus
Tài liệu hướng dẫn góc chính thức khá tốt: https://angular.io/guide/http#setting-new-headers – CodeWarrior