【问题标题】:Angular 2 Two-way Binding updates mock service constantAngular 2双向绑定更新模拟服务常量
【发布时间】:2017-03-29 21:35:50
【问题描述】:

在阅读“英雄之旅”Angular 2 教程时,我注意到当ngModel 发生更改时,更改会传播到使用相同对象的其他组件。但是当我尝试在控制台上记录模拟服务常量HEROES时,它的值也发生了变化。

mock-heroes.ts

import { Hero } from './shared/hero.model';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
];

hero.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero.model';
import { HEROES } from '../mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    console.log(HEROES); // print the constant HEROES value
    return Promise.resolve(HEROES);
  }
}

hero-detail.component.html

<div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="hero.name" placeholder="name"/>
  </div>
</div>

heroes.component.html

<h3>My Heroes</h3>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
<hero-detail [hero]="selectedHero"></hero-detail>

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from './shared/hero.model';
import { HeroService } from './shared/hero.service';

@Component({
  selector: 'my-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes);
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}

HeroService 是从 AppModule 提供者数组(全局服务提供者)注入的。

通过输入将名称从“Narco”更改为“Narcosssss”:

更新控制台上看到的常量HEROES

有人可以向我解释一下它是如何工作的吗?

【问题讨论】:

    标签: angular typescript 2-way-object-databinding


    【解决方案1】:

    您的hero 对象在您的整个应用中具有相同的引用。因此,如果您更改引用的对象。该属性将在任何被引用的地方发生变化。

    【讨论】:

    • 所以HEROES常量也被引用了?知道HEROES 只能通过服务访问,我看不到代码的哪一部分引用了它。这真的让我很困惑。
    • 您正在使用getHeroes 方法获取HEROES;它不是给你一个新对象,而是给你“那个”对象。然后分配this.heroes = heroesheroes 是“那个”对象,并且您将“那个”对象引用传递给this.heroes
    • 谢谢你,我刚刚了解到,在JS中,当一个变量引用一个对象(包括一个数组)并且你改变它的属性时,被引用对象的属性也会改变。直到现在我才真正知道这一点,因为我还没有遇到任何应用这个概念的情况。 :)
    • @RaxWeber 很高兴我能帮上忙 :-)
    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2017-04-29
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多