作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有一个应用程序模块和单组件应用程序(用于演示我的问题),并出现以下错误:
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)模块下的任何组件。
这是我正在看的例子。
我正在使用 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/
我是一名优秀的程序员,十分优秀!