简体   繁体   English

Angular 提供的服务:'root' 为空 object

[英]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.我刚刚在 angular 应用程序中创建了一个全新的服务,并使用 providedIn: 'root' 使其在应用程序的任何地方都可用。

But when I import it and try to use it says its methods are undefined.但是当我导入它并尝试使用它时,它说它的方法是未定义的。

Here is the code这是代码

service.ts服务.ts

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

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

component.ts组件.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()尝试在 providers 中添加您想要注入的服务:[ ] 在您的 core.module 和您的 AccountService 中将 @Injectable({ providedIn: 'root' }) 替换为 @Injectable()

@ChrisHamilton you are right, an imported module to that service caused the issue, it was not provided anywhere. @ChrisHamilton 你是对的,该服务的一个导入模块导致了这个问题,它没有在任何地方提供。 Added providedIn: root to there was solved the issue.添加 providedIn: root 到那里解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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