user13734003
user13734003

Reputation:

NullInjectorError: No provider for xxx With Injector

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

Answers (3)

tonderaimuchada
tonderaimuchada

Reputation: 233

I encountered the same error using Angular 9 and I solved by:

  1. By adding the @Injectable() annotation to the component that was to be used/referenced from another component, as: @Injectable({ providedIn: 'root' }) export class BankComponent {}

  2. 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

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

Nikita Reutov
Nikita Reutov

Reputation: 36

You should provide your service in your module where you got the component

Upvotes: 1

Related Questions