POV
POV

Reputation: 12005

Inject service in provider Angular 5?

I have simple custom service in Angular 5:

@Injectable()
export class RequestsMethods {
  constructor(private http: HttpService) {
  }

}

I tried to register this as provider in @NgModule({}):

providers: [
    RequestsMethods,
    FormRegister,
    ErrorWatcher,
    {
      provide: HttpService,
      useFactory: httpFactoryService,
      deps: [Router, XHRBackend, RequestOptions]
    }
  ],

Then in component I used:

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [RequestsMethods]

});

And component constructor:

constructor(private requestMethods: RequestsMethods){}

After compiling it gives me an error:

Error: StaticInjectorError(AppModule)[HttpService -> XHRBackend]:
StaticInjectorError(Platform: core)[HttpService -> XHRBackend]: NullInjectorError: No provider for XHRBackend! at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:1060) at resolveToken (core.js:1298) at tryResolveToken (core.js:1242) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1139) at resolveToken (core.js:1298) at tryResolveToken (core.js:1242) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1139) at resolveNgModuleDep (core.js:8374) at _callFactory (core.js:8442) at _createProviderInstance (core.js:8394)

If delete constructor from RequestsMethods and register RequestsMethods in providers it works fine

Upvotes: 0

Views: 1029

Answers (1)

Naseem Ahamed
Naseem Ahamed

Reputation: 129

1) In your app.module.ts,

-- import and register RequestsMethods under providers.
-- import and register BrowserModule and HttpClientModule under imports.

@NgModule({
 imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  providers: [RequestsMethods],
})

2) Import and inject the RequestMethods service into your desired component.

constructor(private requestMethods: RequestsMethods){}

For your use case, do not 'provide' the RequestMethods service at the component level.

i.e.:

In your component, the following line is enough

constructor(private requestMethods: RequestsMethods){}

Remove this -> providers: [RequestsMethods] in your @Component annotation

Explanation:

Provider lets the dependency injection system to know "how to obtain a value for a dependency".

When you add a service provider to the app.module.ts (root module), it is available throughout the app.

You should always try to provide your desired service in the root module unless if you want the service to be available only if a particular @NgModule is imported.

Upvotes: 1

Related Questions