4
votes

I'm new in angular6, when I send a parameter from component to service, I get StaticInjectorError. What is wrong?

My code is something like this component:

import { Component, Input, OnInit } from '@angular/core';
import { myService } from '../../@core/data/myService';
@Component({
  selector: 'table',
  templateUrl: './table.component.html'
})
export class TableComponent implements OnInit {
  constructor(private service: myService) {
  }
  ngOnInit() {
    this.service = new myService ("name");
}

service:

 import { Injectable, Inject } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { DataService } from './data.service';

    @Injectable() export class myService {

        constructor(
            entityName: string,
        ) {
            console.log(entityName);
        }
    }

app.module.ts:

import { myService } from './@core/data/myService '
import { TableModule } from './pages/table/table.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,

    NgbModule.forRoot(),
    ThemeModule.forRoot(),
    CoreModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    myService,
    TableModule
  ],
})
export class AppModule {
}

error message: ProductsComponent.html:1 ERROR Error: StaticInjectorError(AppModule)[BDBaseService -> String]: StaticInjectorError(Platform: core)[BDBaseService -> String]: NullInjectorError: No provider for String! at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:979) at resolveToken (core.js:1232) at tryResolveToken (core.js:1182) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1077) at resolveToken (core.js:1232) at tryResolveToken (core.js:1182) at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1077) at resolveNgModuleDep (core.js:9238) at _createClass (core.js:9283) at _createProviderInstance$1 (core.js:9255)

1
Show you app.module.ts file.Karnan Muthukumar

1 Answers

5
votes

You don't do this.service = new myService ("name");. Service is created the moment it is provided somewhere. In your case, in app.module.ts. Which means that only one instance of this service will be used through whole application. If you want multiple instances, you have to provide it again in either module or component. If service is provided several times on different levels (e.g. both in app.module and in component), the service provided on lowest level is used.

To provide service in component, simply add line to your @Component decorator:

@Component({
    selector: 'table',
    templateUrl: './table.component.html',
    providers: [myService], // <---
})

If you absolutely need to pass some value to this service at the time it is constructed, see this answer (I hope it is still actual)