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

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

问题描述

我有一个 salary.service 和一个 player.component,如果在服务中更新了工资变量,播放器组件中的视图会更新吗?或者在 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.

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

}

编辑

对于想了解我如何解决问题的任何人,这里是 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);
    };
}

最后,这里有一个你可以弄乱的 plunker:http://plnkr.co/edit/oChP0joWuRXTAYFCsPbr?p=preview

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

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

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