Angular 2 Service Two-Way Data Binding

后端 未结 1 1109
日久生厌
日久生厌 2021-01-14 16:13

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

相关标签:
1条回答
  • 2021-01-14 16:46

    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

    0 讨论(0)
提交回复
热议问题