Angular 2服务双向数据绑定

时间:2016-11-03 19:52:37

标签: angular typescript angular2-services

我有一个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

1 个答案:

答案 0 :(得分:1)

不,你定义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