Angular 5, NullInjectorError: No provider for Service
You need to add TesteventService under providers under imports in your app.module.ts
providers: [
TesteventService
]
There are two possibilities to solve this problem:
- You can provide your service name in app.module.ts providers array like this way and error will be gone:
imports: [ ], declarations: [ ], providers: [ TesteventService ]
- For some of the latest versions of angular you can simply annotate you desired service this way:
@Injectable({ providedIn: 'root' })
Here is how i have solved my problem with how to pass runtime parameter to a angular service which is part of another custom library
It was difficult to identify where and how to provide injected parameter
Here my AuthService is part of another library i used providedIn: 'root' because my service requirement was to define it as a singleton service. And there are many ways to achieve that ...
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(
@Inject('defaultUserName') private defaultUserName: string,
@Inject('defaultPassword') private defaultPassword: string
) {
// Now you can use injected parameters
console.log("defaultUserName", defaultUserName);
console.log("defaultPassword", defaultPassword);
}
// More code and methods
}
Here is how i use above service in my project
import { CoreApiModule } from 'my-library/app';
import { **AuthService** } from 'my-library/app/api/auth.service';
@NgModule({
imports: [
CoreApiModule
],
declarations: [
],
bootstrap: [AppComponent],
providers: [
AuthService,
{
provide: 'defaultUserName',
useValue: Constants.userName,
},
{
provide: 'defaultPassword',
useValue: Constants.defaultPassword,
}
]
})
export class AppModule {}
Now you can directly import AuthService in any component and start using it.