【发布时间】:2016-05-30 20:38:10
【问题描述】:
我正在尝试向组件注入服务并收到以下消息
异常:TypeError:无法读取未定义的属性“getDemoString”
据我了解,该服务没有被注入。
组件
import {Component, OnInit} from 'angular2/core'
import {DemoService} from './demo.service'
@Component({
selector: 'gtbe-navbar',
templateUrl: 'app/navbar.component.html',
providers: [DemoService]
})
export class Navbar implements OnInit {
name: string;
constructor(private _service: DemoService) { }
ngOnInit() {
this.name = this._service.getDemoString();
}
}
服务
import {Injectable} from 'angular2/core'
@Injectable()
export class DemoService {
getDemoString() {
return "demo";
}
}
【问题讨论】:
-
您使用的是哪个版本的 Angular 2?由于 RC 已经发布,因此使用它是有意义的(但显然你的导入背叛了你没有这样做)。
-
这很奇怪。我有一项服务,其代码与您几乎相同,并且运行良好。请尝试从服务中的
angular2/core导入Inject类并检查是否有效。 -
一切对我来说都很好。确保服务导入路径正确。请提及您的 Angular 版本。
-
@guicl 我尝试使用 Inject,但效果不佳,我的角度版本是 "angular2": "^2.0.0-beta.17", "systemjs": "^0.19. 27”,“es6-promise”:“^3.0.2”,“es6-shim”:“^0.35.1”,“反射元数据”:“^0.1.2”,“rxjs”:“5.0.0 -beta.6", "zone.js": "^0.6.12
-
按预期工作 - 请参阅Plunker。我认为你的安装有点无聊。
标签: angularjs angular angular2-services