简体   繁体   中英

How to create object which can be modified by multiple angular2 component?

How to create object which can be modified by multiple angular2 component.

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
  }
}

In Home.ts result is " Brad" which is not modified by App.ts I want result to be "Brad_Changed" which was modified by App.ts. How do I write my PeopleService.ts and how to pass it by reference to other component in angular2?

Just remove PeopleService from Home component bindings. By adding this binding, you're creating new instance of PeopleService for Home component and all its children:

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
  }
}

See this plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM