Home > Back-end >  Angular service with providedIn: 'root' is an empty object
Angular service with providedIn: 'root' is an empty object

Time:04-22

I just created a brand new service inside an angular application and use providedIn: 'root' to make it available anywhere in the application.

But when I import it and try to use it says its methods are undefined.

Here is the code

service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Service {
  public publicMethod() {}
}

component.ts

import { Service } from 'path/to/service';
import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
    selector: 'footer',
    templateUrl: './footer.component.html',
})
export class FooterComponent {
  constructor(private readonly service: Service) {
     this.service.publicMethod // undefined
  }
}

Other services imported the same way are working fine. What can cause this issue?

CodePudding user response:

Try to add your service you want to inject in providers : [ ] in your core.module and in your AccountService replace @Injectable({ providedIn: 'root' }) with @Injectable()

CodePudding user response:

@ChrisHamilton you are right, an imported module to that service caused the issue, it was not provided anywhere. Added providedIn: root to there was solved the issue.

  • Related