Reputation: 227
Basically I have a provider running on app initialization. One service is being injected fine no problem, but the other is returning undefined. I tried putting a console.log statement on both of their constructors and they are both running before my provider so I have NO idea why only one of them is undefined when I try to use it.
All Help is appreciated.
Here's my code. If you need more let me know.
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){
}
// ...
}
Thanks in advance
Upvotes: 2
Views: 4609
Reputation: 10790
Well sorry to mislead you. inject
function only injects tokens it seems. So we can use INJECTOR
token to inject a service injector into our token. So it became sth like this:
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 {}
Here is the working Stackblitz example.
Upvotes: 3