Angular 2 服务双向数据绑定

Angular 2 Service Two-Way Data Binding

我有一个 salary.service 和一个 player.component,如果工资变量在服务中更新,播放器组件中的视图是否会更新?或者 Angular 2 中不是这种情况?

首次加载页面时,我在 player.component 视图中看到了 50000,所以我知道这两者正在协同工作。它正在更新让我感到困惑的值。

salary.service

export class SalaryService {

    public salary = 50000; // starting value which gets subtracted from

    constructor() { }

    public setSalary = (value) => { this.salary = this.salary - value };

}

player.component

export class PlayerComponent {

    constructor(private salaryService:SalaryService) {}

    public salary = this.salaryService.salary;

    public updateSalary = (value) => { this.salaryService.setSalary(value) };

}

编辑

对于任何想了解我如何解决问题的人,这里是 Plunker:

http://plnkr.co/edit/aFRXHD3IAy0iFqHe5ard?p=preview

不,您定义 public salary = this.salaryService.salary 的方式是复制值而不是分配对薪水的引用。它们在内存中是不同的实例,因此不能指望玩家组件中的薪水与服务中的薪水相同。

如果你有一个带薪水的球员并将其传递给服务进行操作,那么视图将正确调整,因为它会在正确的对象上操作。

那看起来像: salary.service.ts

import {Injectable} from "@angular/core";

@Injectable()
export class SalaryService {
    constructor() { }

    public setSalary = (player, value) => {
      player.salary -= value;
    };

}

player.component.ts

import { Component } from "@angular/core";
import { SalaryService } from "./salary.service";

@Component({
  selector: 'player',
  template: `
  <div>{{player.salary}}</div>
  <button (click)="updateSalary(player, 50)" type="button">Update Salary</button>
  `
  providers: [SalaryService]
})
export class PlayerComponent {
    player = { id: 0, name: "Bob", salary: 50000};
    constructor(private salaryService:SalaryService) {

    }

    public updateSalary = (player, value) => {
      this.salaryService.setSalary(player, value);
    };
}

最后,这是一个你可以随意使用的插件:http://plnkr.co/edit/oChP0joWuRXTAYFCsPbr?p=preview