0

I'm trying to inject additional parameters to my service. I'm following this tutorial https://www.techiediaries.com/pass-parameters-angular-10-service-inject/

But when I run my program I get NullInjectorError: No provider for param!

Should this even work because that look so simple I can't understand what I possibly can do wrong there.

Why I need to do this is a have a service that will need to know object id to work properly. How to get this id depends on where this service is injected.

But to get things going I'd like to get this hard coded value work first.

PS. If I delete that private param: string from service constructor service gets injected correctly.

kivikall
  • 786
  • 2
  • 13
  • 29

1 Answers1

1

you need to provide your parameter from somewhere in the app.module.ts providers array:

for example, an apiUrl field got from environments file:

providers: [
    {
      provide: 'apiUrl',
      useValue: environment.apiUrl
    },
  ],

where apiUrl is declared in environment.ts file.

then, inject in your service by the constructor:

constructor(
    private http: HttpClient,
    @Inject('apiUrl') private baseUrl: string
  ) {
  }

updated: passing service parameter from component

"You can put the providers in the component, if the service itself also is provided in the component. The values need to be provided at the same level as the service or higher."

AlleXyS
  • 2,476
  • 2
  • 17
  • 37
  • Okey, thanks. According to that tutorial it would have been possible to provide it from component but I guess it's incorrect then? I was now able to provide additional params from my sub modules by changing service's Injectable providedIn from 'root' to 'any'. If I keep it as 'root' then indeed I can provide values from app.module.ts but it doesn't serve the purpose anymore as I need to provide different values depending on which module my service is injected into. – kivikall Apr 23 '21 at 08:35
  • To be honest, I never tried to provide a value from the component. Try using @Optional() operator inside your service constructor. Maybe https://stackoverflow.com/questions/42396804/how-to-write-a-service-that-requires-constructor-parameters helps you – AlleXyS Apr 23 '21 at 08:47
  • 1
    Thanks, that link actually helped. Answer was there within the comments. I'll paste it here for possible future visitor: "You can put the providers in the component, if the service itself also is provided in the component. The values need to be provided at the same level as the service or higher." – kivikall Apr 23 '21 at 08:52
  • I'll mark you initial reply as an answer. I don't know if this really helps me on what I'm trying to achieve but I think my question got answered. Bottom line is I think that tutorial I was following was incorrect or incomplete. – kivikall Apr 23 '21 at 08:56
  • thanks. I updated my answer with the solution and had linked it to that topic. – AlleXyS Apr 23 '21 at 09:24