如何从 ng generate library 生成的库中共享 Angular 服务?

How to share Angular service from the library generated by ng generate library?

我正在尝试将我使用 ng g library 生成的 npm 包中的服务与托管 angular 应用程序共享。我知道如何为组件或指令做这件事,但是当涉及到服务时我就迷路了。

在库中我有以下文件:

所有内容都在 public-api.ts 中提及,我可以将它们导入我的托管应用程序。

authentication.service.ts:(没有providedIn: 'root'我也试过了)

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

authentication.module.ts:

@NgModule({
})
export class AuthenticationModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthenticationModule,
      providers: [AuthenticationService]
    };
  }
}

托管应用程序的 app.module.ts:

import { AuthenticationService } from '@custom/lib';
import { AuthenticationModule } from '@custom/lib';

export function appInitFactory(
    injector: Injector,
    authenticationService: AuthenticationService,
    configService: ConfigService
  ): any {
    return () =>
      loadConfig(configService, authenticationService)
        .then(() => checkLogIn(injector, authenticationService));
}

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AuthenticationModule.forRoot()
  ],
  providers: [
    AuthenticationService,
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    },
    {
      provide: APP_INITIALIZER,
      useFactory: appInitFactory,
      deps: [Injector, AuthenticationService, ConfigService],
      multi: true,
    }

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我想将 AuthenticationService 注入 appInitFactory 因为我正在从 JSON 文件加载应用程序配置并在初始化托管应用程序之前检查身份验证。

我得到的错误是:

core.js:15723 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticationService]: 
  StaticInjectorError(Platform: core)[AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!
Error: StaticInjectorError(AppModule)[AuthenticationService]: 
  StaticInjectorError(Platform: core)[AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get

有谁知道可能导致此错误的原因是什么? 提前谢谢你。

@Injectable({
  providedIn: 'root'
})

不需要。只需使用

@Injectable()

因为您已经在 forRoot 方法中提供了它。