简体   繁体   中英

Angular service with providedIn: 'root' is an empty object

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?

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM