我有一个在我的Angular2(2.0.0-beta.0)应用程序中定义的服务。它类似于以下内容:
import {Injectable} from "angular2/core";
@Injectable()
export class MyService {
constructor() {
}
getSomething() {
return 'something';
}
}
我已将它列在我的主应用程序文件中的bootstrap()函数中,以便它可以在我的代码中通用地使用:
bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);
有时候我无法在组件中使用服务,即使在组件的构造函数中有类似于
myService:MyService
这样的东西。如下所示:import {MyService} from '../services/my.service';
@Component({
selector: 'my-component',
directives: [],
providers: [],
pipes: [],
template: `
<div><button (click)="doStuff()">Click Me!</button></div>
`
})
export MyComponent {
constructor(myService:MyService) {} // note the private keyword
doStuff() {
return this.myService.getSomething();
}
}
在其他地方它能够正常工作。但在一些地方,如果我尝试访问它,就会收到类似以下的错误信息:
EXCEPTION: TypeError: Cannot read property 'getSomething' of undefined
基本上意味着该服务未被注入。
是什么导致它未被注入?