【问题标题】:Angular 6+ providedIn: 'root' raising a StaticInjectorErrorAngular 6+ providedIn: 'root' 引发 StaticInjectorError
【发布时间】:2019-08-23 11:49:23
【问题描述】:

我在谷歌上进行了广泛的搜索,但似乎找不到其他人遇到此问题,所以我一定遗漏了一些东西。我正在将我的所有 AppModule 服务转换为使用 providedIn: 'root' 方法,但它似乎不起作用。

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

Injectable({
    providedIn: 'root'
})
export class CommonService{
    UserName : string = 'Guest';
    Roles : Array<any> = [];
    Theme: string = 'standard';

    constructor(){}
}

这是使用该服务的组件之一:

import { CommonService } from './Services/common.service';

@Component({
    selector: 'navBar',
  templateUrl: './navbar.html'
})

export class NavBar {

    constructor(private session: CommonService) {}

在运行时,这是控制台中的错误:

StaticInjectorError(AppModule)[NavBar -> CommonService]: StaticInjectorError(平台:核心)[NavBar -> CommonService]: NullInjectorError: 没有 CommonService 的提供者!

我检查了文档,但我看不出哪里出错了。我错过了什么?

忘了说,NavBar 是在 SharedModule 中声明的组件,SharedModule 是在 AppModule 中导入的。

【问题讨论】:

    标签: dependency-injection angular6


    【解决方案1】:

    您可能缺少 Injectable 上的前导“@”:

    import { Injectable } from '@angular/core';
    
    @Injectable({
        providedIn: 'root'
    })
    export class CommonService{
        UserName : string = 'Guest';
        Roles : Array<any> = [];
        Theme: string = 'standard';
    
        constructor(){}
    }
    

    IDE 中可能没有错误,但看起来可能是问题所在

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 2019-02-25
      • 1970-01-01
      • 2023-02-21
      • 2018-11-29
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多