业力:无法读取拦截器中未定义的属性

时间:2018-08-14 12:48:14

标签: angular karma-jasmine

我的业力出现错误,我的测试失败:

Uncaught Error: Uncaught (in promise): TypeError: Cannot read property 'hasPortalTokenInLocalStorage' of undefined
TypeError: Cannot read property 'hasPortalTokenInLocalStorage' of undefined
    at AuthenticationInterceptor.intercept (authentication.interceptor.ts:22

奇怪的是,它发生在完全不同的测试中,我什至不应该使用该方法。

拦截器失败的代码行如下:

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

constructor(private authService: AuthenticationService) { }

public intercept(request: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {

    // The error happens here.
    if (this.authService.hasPortalTokenInLocalStorage()) {

            const ticketId: string = this.authService.getPortalTokenFromLocalStorage() as string;

            let headers: HttpHeaders = new HttpHeaders();
            headers = headers.append('Authorization', ticketId);

            request = request.clone({ headers });
        }

        return next.handle(request);
    }
}

因此由于某种原因,它无法注入AuthenticationService。

有人有主意吗?

@更新 像这样在我的authentication.module(在core.module中导入,在app.module中导入)中提供拦截器:

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthenticationInterceptor,
      multi: true
    }
  ]
})
export class AuthenticationModule { }

我的AuthenticationService如下:

import { Injectable } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  private readonly localStorageParamName: string = 'portal.token';
  private readonly urlParamName: string = 'ticketId';

  constructor(private activatedRoute: ActivatedRoute) { }

  public getPortalTokenFromLocalStorage(): string | null {
    return localStorage.getItem(this.localStorageParamName);
  }

  public hasPortalTokenInLocalStorage(): boolean {
    return localStorage.getItem(this.localStorageParamName) != null;
  }

  // More methods here...

}

0 个答案:

没有答案