简体   繁体   English

无法将服务正确地注入HttpInterceptor

[英]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.

相关问题 无法在 HttpInterceptor 中注入 ngx-toastr 服务 - Can't inject ngx-toastr service in HttpInterceptor NativeScript中的httpinterceptor无法正常工作 - httpinterceptor in NativeScript not working properly 当我在HttpInterceptor类中注入一个使用HttpClient的服务时,Angular 6进入无限循环依赖循环 - Angular 6 enters infinite loop of cyclic dependency when I inject a service that uses HttpClient inside my HttpInterceptor class HttpInterceptor中的注入服务未初始化 - Injected Service in HttpInterceptor not initialized 无法在 Angular 服务中注入 NotifierService - Unable to inject NotifierService in a Angular Service 无法在 http 拦截器中注入服务 - Unable to inject service in http interceptors 无法将服务注入服务以进行测试 - Unable to inject service into service for testing purposes Angular2:无法将服务注入另一个服务 - Angular2 : Unable to Inject a service into another service 有没有办法注入观察:来自Angular 6的HttpInterceptor的“响应”? - Is there a way to inject observe: 'response' from HttpInterceptor in Angular 6? 无法将“ Route”或“ ActivatedRouteSnapshot”注入“ HttpInterceptor” - Can't inject `Route` nor `ActivatedRouteSnapshot` into `HttpInterceptor`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM