无法在angular2中导入服务
我正在努力用angular2导入一个简单的服务。请帮我纠正这个问题。我知道我遗漏了一些非常简单的东西,但却找不到。 提前谢谢无法在angular2中导入服务,angular,angular2-services,Angular,Angular2 Services,我正在努力用angular2导入一个简单的服务。请帮我纠正这个问题。我知道我遗漏了一些非常简单的东西,但却找不到。 提前谢谢 //我们的根应用程序组件 从'angular2/core'导入{Component,OnInit} 从“/app.service”导入{DataService} @组成部分({ 选择器:“我的应用程序”, 提供者:[数据服务], 模板:` 你好{{name} `, }) 导出类应用程序实现OnInit{ 构造函数(服务:数据服务){ this.name='Angular
//我们的根应用程序组件
从'angular2/core'导入{Component,OnInit}
从“/app.service”导入{DataService}
@组成部分({
选择器:“我的应用程序”,
提供者:[数据服务],
模板:`
你好{{name}
`,
})
导出类应用程序实现OnInit{
构造函数(服务:数据服务){
this.name='Angular2'
}
恩戈尼尼特(){
console.log(this.service)//此处未定义打印
this.name=this.service.setName('test');
}
}
我不知道你要找的是不是这个,普朗克
如果是这样,你可以改变
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(public service: DataService) {
this.name = 'Angular2'
}
ngOnInit(){
this.service.setName('test');
this.name = this.service.getName();
console.log(this.service.getName());
}
}
从'angular2/core'导入{Component,OnInit}
从“/app.service”导入{DataService}
@组成部分({
选择器:“我的应用程序”,
提供者:[数据服务],
模板:`
你好{{name}
`,
})
导出类应用程序实现OnInit{
构造函数(公共服务:数据服务){
this.name='Angular2'
}
恩戈尼尼特(){
this.service.setName('test');
this.name=this.service.getName();
console.log(this.service.getName());
}
}
您必须告诉您的构造函数它是一种什么样的服务。例如“公共”或“私人”
这本质上就是,什么可以看到这个服务,只有这个类才能看到这个服务?如果是私人的,否则就公开
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(public service: DataService) {
this.name = 'Angular2'
}
ngOnInit(){
this.service.setName('test');
this.name = this.service.getName();
console.log(this.service.getName());
}
}
constructor(public service: DataService) {
this.name = 'Angular2'
}