Angular 2服务双向数据绑定 [英] Angular 2 Service Two-Way Data Binding

查看:100
本文介绍了Angular 2服务双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个salary.serviceplayer.component,如果在服务中更新了salary变量,是否会更新播放器组件中的视图?还是在Angular 2中不是这种情况?

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?

页面第一次加载时,我在player.component视图中看到50000,所以我知道两者是一起工作的.它正在更新让我感到困惑的价值.

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.

工资服务

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:

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

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

推荐答案

否,您定义public salary = this.salaryService.salary的方式是复制值,而不是给薪金分配参考.它们是内存中的不同实例,因此不能期望播放器组件中的薪水与服务中的薪水相同.

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.

这看起来像: 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 =预览

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

这篇关于Angular 2服务双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆