感谢所有帮助。
这是我的代码。如果您需要更多,请告诉我。
AppModule
@NgModule({
declarations: [
// ...
],
entryComponents: [
// ...
],
imports: [
// ...
],
providers: [
AppProvider,
// ...
{
provide: APP_INITIALIZER,
useFactory: (provider: AppProvider) => () => provider.load(),
deps: [AppProvider],
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule {
}
AppProvider
@Injectable({providedIn: 'root'}) export class AppProvider { constructor( // ... private participantService: ParticipantService, private dstService: DSTService) { } load() { //... console.log(participantService); // prints undefined console.log(dstService); // prints the service // ... return Promise.resolve(); } }
ParticipantService
@Injectable({providedIn: 'root'}) export class ParticipantService { // ... constructor(private http: HttpClient, // ... private router: Router){ } // ... }
DSTService
@Injectable({providedIn: 'root'}) export class DSTService{ // ... constructor(private http: HttpClient, private participantService: ParticipantService, // ... private router: Router){ } // ... }
提前感谢
inject
函数似乎只注入令牌。因此,我们可以使用INJECTOR
令牌将服务注入程序注入到我们的令牌中。这样就变成了……:import { SOME_TOKEN } from "./token";
import { NgModule, inject, INJECTOR } from "@angular/core";
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
providers: [
HelloService,
{
provide: SOME_TOKEN,
useFactory: () => {
return inject(INJECTOR)
.get(HelloService)
.getHello();
}
}
]
})
export class AppModule {}
这里是有效的Stackblitz示例。