我在把一个类加载到一个角分量时遇到了问题。我已经尝试了很长一段时间来解决这个问题,我甚至尝试将所有这些都加入到一个文件中。我拥有的是:
Application.ts
/// <reference path="../typings/angular2/angular2.d.ts" />
import {Component,View,bootstrap,NgFor} from "angular2/angular2";
import {NameService} from "./services/NameService";
@Component({
selector:'my-app',
injectables: [NameService]
})
@View({
template:'<h1>Hi {{name}}</h1>' +
'<p>Friends</p>' +
'<ul>' +
' <li *ng-for="#name of names">{{name}}</li>' +
'</ul>',
directives:[NgFor]
})
class MyAppComponent
{
name:string;
names:Array<string>;
constructor(nameService:NameService)
{
this.name = 'Michal';
this.names = nameService.getNames();
}
}
bootstrap(MyAppComponent);services/NameService.ts
export class NameService {
names: Array<string>;
constructor() {
this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
}
getNames()
{
return this.names;
}
}我不断收到一条错误消息,上面写着No provider for NameService。
有人能帮我找出代码的问题吗?
发布于 2015-08-30 16:55:30
发布于 2016-12-19 14:37:25
您应该在NameService的providers数组中注入AppModule的NgModule元数据。
@NgModule({
imports: [BrowserModule, ...],
declarations: [...],
bootstrap: [AppComponent],
//inject providers below if you want single instance to be share amongst app
providers: [MyService]
})
export class AppModule {
}如果您想要为特定组件级别创建一个依赖项,而不需要考虑应用程序的状态,那么您可以注入该依赖于组件providers元数据选项,如所示的已接受的@Klass答案。
发布于 2018-08-14 17:59:53
令人震惊的是,最新版本的角6博士 :-)的语法又发生了变化。
从角6.0开始,创建单例服务的首选方法是在应用程序根中指定应该提供的服务。这是通过将providedIn设置为服务的@Injectable装饰器的根来完成的:
src/app/user.service.0.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}https://stackoverflow.com/questions/30580083
复制相似问题