2

我正在努力在 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');
  }
}
4

2 回答 2

3

你必须告诉你的构造函数它是什么类型的服务。例如“公共”或“私人”。

constructor(public service: DataService) {
    this.name = 'Angular2'
  }

这本质上就是,什么能看到这个服务,只有这个类才能看到这个服务?如果是,则为私有,否则为公开。

于 2016-03-10T01:12:00.740 回答
1

我不知道这个,plunker,是不是你要找的,

Plunker

如果是这样你可以改变

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());
  }

}
于 2016-03-10T01:02:03.373 回答