Mike
Mike

Reputation: 1768

Angular 2 Service Two-Way Data Binding

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

Upvotes: 3

Views: 6173

Answers (1)

silentsod
silentsod

Reputation: 8335

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

Upvotes: 1

Related Questions