Angular 2: Missing provider (for injection)

I have two services in my application - MainService and RightClickService. Only the MainService is available globally in the application, and the RightClickService is entered into the MainService. Therefore, I defined the following files as:

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MainService],
  bootstrap: [AppComponent]
})
export class AppModule { }

RightClickService is not mentioned in app.module.ts.

service.ts

 @Injectable()
 export class MainService {

  constructor(private rightClickService: RightClickService) {
    console.log("Constructor is init");
  }
}

RightClickService exists in only one component with a name inside the large RightClickComponent application.

right click click.component.ts:

@Component({
  selector: 'right-click',
  template: `
    ...
  `,
  styleUrls: ['...'],
  providers: [RightClickService]
})
export class RightClickComponent implements OnInit {

  constructor(private rightClickService: RightClickService) {}

}

However, I get an error message:

EXCEPTION: No provider for RightClickService!

Do you know what I am doing wrong?

+6
source share
2 answers

In addition to what has already been said, you should know two things:

  • , , @NgModule.providers , AppModule.

  • ( ), , @Component.providers .

angular (RightClickService) (MainService), , NgModules.

angular (RightClickService) (RightClickComponent), , , parent , , , , .

, :

function MainServiceFactory(RightClickService) {
    return new MainService(new RightClickService());
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
   {
     provide: MainService,
     useFactory: MainServiceFactory,
     deps: [RightClickService]
   }
],
  bootstrap: [AppComponent]
})
export class AppModule { }
+7

Plunker, , -... , , , . , - ?

: https://plnkr.co/edit/ea9dFs?p=info

( ... ... .)

import { Injectable } from '@angular/core'

 @Injectable()
 export class RightClickService {

  constructor() {
    console.log("RightClickService is init");
  }
}
+3

Source: https://habr.com/ru/post/1016124/


All Articles