javascript - 添加提供程序@NgModule 时出现 Angular2 "No provider for Service!"错误

标签 javascript angular typescript angular2-modules

我有一个应用程序模块和单组件应用程序(用于演示我的问题),并出现以下错误:

 Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: No provider for UserService! ; Zone: <root> ; Task: Promise.then ; Value:

AppModule 代码:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { UserService } from './components/common/userservice';

@NgModule({
    imports: [
    BrowserModule,
],
declarations: [
    AppComponent
],
providers: [UserService],
bootstrap: [AppComponent],
entryComponents: []

})
export class AppModule {
}

我的 AppComponent 的代码:

import { Component} from '@angular/core';
import { UserService} from './userservice';

@Component({
  selector: 'App',
  template: `<h3>App component</h3>                                                                                      
            user name: {{userName}}
            `,
  providers: []
  })

export class AppComponent  {

  userName: string;
  constructor(userService: UserService) {
      this.userName = userService.userName;   
  }    
}

我的用户服务代码:

import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class UserService {
    obs$: EventEmitter<any> = new EventEmitter<any>()
    userName = 'Sherlock Holmes';
}

现在,如果我将 UserService 作为提供者添加到 AppComponent,它将解决问题。但我不想,因为我只想在整个应用程序中使用我的服务的一个实例。即使在子模块(功能模块)中。

根据我的理解,如果我在模块级别添加服务作为提供者,那么我可以将它注入(inject)模块下的任何组件。

这是我正在看的例子。

Plunker

我正在使用 angular2 版本:“2.0.0”

最佳答案

导入路径错误:你在一个中使用了/Common,在下面使用了/common

Visual Studio 和 WebStorm 不会显示路径区分大小写的 IntelliSense 错误。

此外,如果使用 Angular 5 的 AoT 模板编译,您可能会收到“此组件不是模块的一部分”错误,即使它是,因为导入路径不正确。如果没有 AoT,这将起作用,因此在转换为 AoT 时您会感到惊讶。

关于javascript - 添加提供程序@NgModule 时出现 Angular2 "No provider for Service!"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41146084/

相关文章:

javascript - AngularJS 指令不起作用

javascript - 在类内部使用时,事件处理程序报告元素未定义

javascript - 如果自上次运行以来没有任何变化,TSLint 是否有阻止运行的选项?

javascript - 具有 Store 调度操作的 Angular 单元测试组件

javascript - react : Update child with parent state change

javascript - Angular 2 Material 2日期选择器日期格式

javascript - 使用 date-fns 的 max 函数从日期字符串数组中查找最大日期

带有私有(private)成员的 Typescript 接口(interface)

Angular tabView primeNG 路由

javascript - 检测页面上 javascript 事件的注入(inject)