Reputation:
I have the following service:
@Injectable()
export class StudentService {
constructor() { }
getDataFormStudentService() {
return "Hi, I'm Mix";
}
}
Now that, I want to use the service above in app.components.ts
:
title = '';
public studentService: StudentService;
constructor(
private injector: Injector) {
this.studentService = this.injector.get(StudentService);
}
ngOnInit(): void {
this.title = this.studentService.getDataFormStudentService();
}
When I run my project I get the following error :
ERROR NullInjectorError: R3InjectorError(AppModule)[StudentService -> StudentService -> StudentService]: NullInjectorError: No provider for StudentService!
Upvotes: 0
Views: 2349
Reputation: 233
I encountered the same error using Angular 9 and I solved by:
By adding the @Injectable() annotation to the component that was to be used/referenced from another component, as: @Injectable({ providedIn: 'root' }) export class BankComponent {}
By adding the injectable-marked component as a parameter to the constructor of my other component as: constructor(private bankComponent: BankComponent) { }
I hope that this will work for you too.
Upvotes: 0
Reputation: 61
You can use providers property under the @Component annotation. It will inject only to your component, and it will create a new instance of the service all the time when your component has been loaded.
@Component({
/* . . . */
providers: [StudentService]
})
Upvotes: 0
Reputation: 36
You should provide your service in your module where you got the component
Upvotes: 1