在 Angular 2 中将服务注入服务时出现无效提供者错误

问题描述 投票:0回答:2

我目前有一个如下所示的模块设置(摘录);

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
。当我尝试在
AuthService
中的
AuthRouteGuard
类中使用
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 { }
javascript angular authentication angular-services angular-dependency-injection
2个回答
0
投票

authHttpServiceProvider
添加到模块的导入中。它导出到全局并且不可用于模块。因此您无法提供服务,因为您的模块提供者未知。

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

0
投票

实际问题出在

AuthService
本身。

AuthModule
定义了一个常量;

export const jwtKey = 'jwt';

正在导入

AuthService
并使用;

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

出于某种原因,如果我删除此导入,一切都会正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.