[英]Unable to inject Service into HttpInterceptor properly
I am using Ionic 4, and Angular 7. I am trying to intercept HTTP requests and add a token to the header. 我正在使用Ionic 4和Angular7。我试图拦截HTTP请求并向标头添加令牌。 The problem is that the
token
is always null when I try retrieving it from AuthService
. 问题是当我尝试从
AuthService
检索token
时, token
始终为null。 I have adding AuthService
to the TokenInterceptor
constructor and also injecting AuthService
. 我已经将
AuthService
添加到TokenInterceptor
构造函数中,并且还注入了AuthService
。 Neither of them work. 他们都不工作。 What am I doing wrong?
我究竟做错了什么?
AuthService.ts AuthService.ts
@Injectable({
providedIn: 'root'
})
export class AuthService
{
public token: string;
public refreshToken: string;
constructor
(
private http: HttpClient,
private storage: StorageService,
)
{
this.API_URL = constants.API_URL;
this.OAUTH_URL = constants.AUTH_URL;
this.storage.getTokens().then(tokens => {
this.token = tokens.access_token;
this.refreshToken = tokens.refresh_token;
});
}
}
TokenInterceptorService TokenInterceptorService
@Injectable()
export class TokenInterceptorService implements HttpInterceptor
{
constructor
(
private auth: AuthService,
)
{
}
setHeaders(req: HttpRequest<any>, token: string): HttpRequest<any> {
return req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{
console.log("token int", this.auth); // I CAN SEE TOKEN HERE
console.log("token int2", this.auth.token); // TOKEN IS UNDEFINED
return next.handle(this.setHeaders(req, this.auth.token));
}
}
Providers array in App.Module.ts App.Module.ts中的Providers数组
providers: [ // .... AuthService, APIService, { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptorService, multi: true, }, ] 提供者:[// .... AuthService,APIService,{提供:HTTP_INTERCEPTORS,useClass:TokenInterceptorService,多:true,},]
I have also tried injecting AuthService but it doesn't work 我也尝试注入AuthService,但是不起作用
@Injectable()
export class TokenInterceptorService implements HttpInterceptor
{
private auth;
constructor
(
private injector: Interjector
)
{
this.auth = this.injector.get(AuthService);
}
setHeaders(req: HttpRequest<any>, token: string): HttpRequest<any> {
return req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{
console.log("token int", this.auth); // I CAN SEE THE TOKEN HERE ALONG WITH ALL OF THE OTHER VARIABLES AND DECLERATIONS IN `AUTHSERVICE`.
console.log("token int2", this.auth.token); // TOKEN IS UNDEFINED
return next.handle(this.setHeaders(req, this.auth.token));
}
}
I have also tried adding AuthService
as a dependency for the TokenInterceptorService
我也尝试过添加
AuthService
作为AuthService
的依赖TokenInterceptorService
providers: [
// ....
AuthService,
APIService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true,
deps: [AuthService],
},
// ....
]
AuthService is bad idea. AuthService是个坏主意。 Because it is the singleton so the token value can't sync, and Storage.getTokens is sync method, you also can't sure AuthService.Token is ready before you use it.
由于它是单例,因此令牌值无法同步,并且Storage.getTokens是sync方法,因此在使用它之前,您也无法确定AuthService.Token已准备就绪。 And others, 1: you can't get new Token if it was updated;
还有其他的1:如果更新了,您将无法获得新令牌; 2: you can't know user already logout.
2:您不知道用户已经注销。
So, please do it in setHeaders method is better. 所以,请用setHeaders方法做的更好。 In my source the logic like it:
在我的资料中,逻辑类似:
//TokenInterceptorService
async setHeaders(url) {
let baseHeader = {/*default values*/};
if (url in sign-in, register, logout, home or other public api) {
return baseHeader;
}
let token = {};
await storage.getToken().then(tokenData => {
token = tokenData;
};
baseHeader.token = token;
return baseHeader;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.