如何创建可以被多个angular2组件修改的对象?

时间:2015-09-23 10:53:20

标签: javascript angular

如何创建可由多个angular2组件修改的对象。

EG。

PeopleService.ts

//a simple service
import {Injectable} from 'angular2/angular2'

@Injectable()
export class PeopleService {
  constructor() {
    this.people = [
      {id: 1, name: 'Brad'},
      {id: 2, name: 'Jules'},
      {id: 3, name: 'Jeff'}
    ];
}
  changeBrad(){
    this.people[0].name = "Brad_Changed";
  }
}

App.ts

import {Component, View} from 'angular2/angular2';
import {PeopleService} from './peopleService';

@Component({
  selector: 'my-app',
  bindings: [PeopleService]
})
@View({
  template: '{{appval}}',
})
export class App{
  appval:string;
  constructor(public peopleService:PeopleService){
    peopleService.changeBrad();
    this.appval = peopleService.people[0].name; // result : Brad_Changed
  }
}

Home.ts

import {Component, View} from 'angular2/angular2';
import {PeopleService} from './peopleService';

@Component({
  selector: 'my-home',
  bindings: [PeopleService]
})
@View({
  template: '{{homeval}}',
})
export class Home{
  homeval:string;
  constructor(public peopleService:PeopleService){
    this.homeval = peopleService.people[0].name; // result : Brad
  }
}

在Home.ts结果是“Brad”,它没有被App.ts修改我希望结果是由App.ts修改的“Brad_Changed”。如何编写我的PeopleService.ts以及如何通过引用angular2?中的其他组件来传递它?

1 个答案:

答案 0 :(得分:3)

只需从PeopleService组件绑定中删除Home即可。通过添加此绑定,您可以为PeopleService组件及其所有子组件创建Home的新实例:

import {Component, View, Host} from 'angular2/angular2';
import {PeopleService} from './peopleService';

@Component({
  selector: 'home',
  // Adding this you're creating new instance of PeopleService for
  // Home component and all its children
  // bindings: [PeopleService]
})
@View({
  template: '<p>{{homeval}}</p>',
})
export class Home{
  homeval:string;
  constructor(peopleService:PeopleService){
    this.homeval = peopleService.people[0].name; // result : Brad
  }
}

请参阅this plunker