我正在努力在 angular2 中导入一个简单的服务。请帮我解决这个问题。我知道我错过了一些非常简单的东西,但找不到它。 提前致谢
http://plnkr.co/edit/Yrh9gC8BMZdtUwy947Za?p=preview
//our root app component
import {Component, OnInit} from 'angular2/core'
import {DataService} from './app.service'
@Component({
selector: 'my-app',
providers: [DataService],
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App implements OnInit{
constructor(service: DataService) {
this.name = 'Angular2'
}
ngOnInit(){
console.log(this.service) // prints Undefined here
this.name = this.service.setName('test');
}
}
最佳答案
你必须告诉你的构造函数它是什么类型的服务。例如“公共(public)”或“私有(private)”。
constructor(public service: DataService) {
this.name = 'Angular2'
}
这本质上就是,什么可以看到这个服务,只有这个类才能看到这个服务吗?如果是,则为私有(private),否则为公开。
关于angular - 无法在 Angular2 中导入服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35905449/