Angular 2 Service Two-Way Data Binding

限于喜欢 提交于 2019-12-01 09:07:20

No, the way that you have it defined the public salary = this.salaryService.salary is copying out the value and not assigning the a reference to salary. They are distinct instances in memory and therefore one cannot expect the salary in the player component to be the same as the one in the service.

If you had a player with a salary and passed it to the service to operate on then the view would adjust correctly as it would be operating on the correct object.

That would look like: 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);
    };
}

Finally, here is a plunker you can mess around with: http://plnkr.co/edit/oChP0joWuRXTAYFCsPbr?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!