0

I want to load api data before app onInit(). I am not able to inject the service dependency.

How I can inject that?

import { GetComissionService } from '../app/services/get-comission.service';


function initializeApp(comissionService: GetCommissionService): Promise<void> {
  return new Promise((resolve, reject) => {
    GetComissionService.getCommission('item').subscribe(data => {
      console.log(data);
      resolve();
     })
  });
}


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [{
    provide: APP_INITIALIZER,
    deps: [GetComissionService],
    useFactory: () => initializeApp,
    multi: true
   }],
  bootstrap: [AppComponent]
})

EDIT 1: adding error message images

Getting these errors while injecting service

enter image description here enter image description here

2
  • You should also call resolve() after you get the data from your service. Commented Nov 22, 2021 at 14:32
  • @OctavianMărculescu I added but I am having issue while injecting the dependency. Its giving error Commented Nov 22, 2021 at 15:17

1 Answer 1

1

You also need to have a parameter on the initializeApp function for the service. Try this:

export function initializeApp(comissionService: GetComissionService): Promise<any> {
  return new Promise((resolve, reject) => {
    comissionService.getCommission('item').subscribe(data => {
      console.log(data);
      resolve();
     })
  });
}
Sign up to request clarification or add additional context in comments.

7 Comments

While adding parameter it says Cannot find name 'GetCommissionService' so removed it.
@IamGrooot, How do you provide GetComissionService for your module?
@sharko I have updated the question with error message picture. Please check
Please note that what my snippet uses is actually the parameter of the function, not the type name as you are using there. Please try to replace your whole function with the snippet I posted (using copy and paste).
I made a typo, I added an extra m in the word comission. Please remove one of the extra ms and you should be good. I also updated the answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.