Angular 2 Service Two-Way Data Binding

a 夏天 提交于 2019-12-01 06:07:01

问题


I have a salary.service and a player.component, if the salary variable gets updated in the service will the view in the player component be updated? Or is that not the case in Angular 2?

When the page first loads I see the 50000 in the player.component view, so I know the two are working together. It's updating the value that's has me stumped.

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

}

EDIT

For anyone who wants to see how I resolved the issue, here's the Plunker:

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


回答1:


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



来源:https://stackoverflow.com/questions/40410112/angular-2-service-two-way-data-binding

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