簡體   English   中英

Angular2-將服務注入服務時出現無效的提供程序錯誤

[英]Angular2 - Invalid provider error when injecting service into service

我目前有一個如下所示的模塊設置(摘錄);

AppModule

  RoutingModule
    AuthRouteGuard

  AuthModule
    LoginFormComponent
    AuthService        

我已經定義我AuthService (負責處理用戶認證和提供了用於確定當前用戶是否被認證的方法),其在我的供應商AuthModule ;

// auth.module.ts - uses https://github.com/auth0/angular2-jwt

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: jwtLocalStorageKey
  }), http, options);
}

export let authHttpServiceProvider = {
  provide: AuthHttp,
  useFactory: authHttpServiceFactory,
  deps: [Http, RequestOptions]
};

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  exports: [AuthComponent],
  declarations: [AuthComponent, LoginComponent, RegisterComponent],
  providers: [
    AuthService,
    authHttpServiceProvider
  ]
})
export class AuthModule { }

我可以在同級LoginFormComponent使用此服務,而不會出現任何問題。 但是,當我嘗試在AuthServiceAuthRouteGuard類中使用RoutingModule時,出現以下錯誤;

Error: Invalid provider for the NgModule 'AuthModule' - only instances of Provider and Type are allowed, got: [?undefined?, ...]

我在AuthModule導入了RoutingModule 上述錯誤一旦發生AuthService被定義為一個依賴AuthRouteGuard ;

export class AuthRouteGuard implements CanActivate {
  constructor(
    private router: Router,
    private authService: AuthService // Removing this injection removes the error
  ) {}

  canActivate() {
    // @todo: if not authenticated
    this.router.navigate(['/login']);

    return true;
  }
}

我在這里缺少什么,為什么在構造函數中注入服務會導致無效的提供程序錯誤,而該錯誤在刪除注入時不會發生?

編輯 -如果完全刪除了authHttpServiceProvider提供程序,則會發生相同的錯誤,因此AuthModule模塊看起來像;

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  exports: [AuthComponent],
  declarations: [AuthComponent, LoginComponent, RegisterComponent],
  providers: [
    AuthService
  ]
})
export class AuthModule { }

authHttpServiceProvider添加到模塊的導入中。 它已導出到全局,無法用於模塊。 因此,由於模塊的提供者未知,因此無法提供服務。

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  exports: [AuthComponent],
  declarations: [AuthComponent, LoginComponent, RegisterComponent],
  providers: [
    AuthService
  ]
})
export class AuthModule { 

實際問題出在AuthService本身內。

AuthModule定義了一個常量;

export const jwtKey = 'jwt';

將其導入到AuthService並使用;

import { jwtKey } from '../auth.module';

由於某種原因,如果我刪除此導入,一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM