Angular 2 双向绑定更新模拟服务常量

Angular 2 Two-way Binding updates mock service constant

在学习 "Tour of Heroes" Angular 2 教程时,我注意到当 ngModel 更改时,更改会传播到使用同一对象的其他组件。但是当我尝试在控制台上记录模拟服务常量 HEROES 时,它的值也发生了变化。

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

英雄-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 providers数组(全局服务提供者)中注入。

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

更新控制台上显示的常量 HEROES

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

您的 hero 对象在整个应用程序中具有 相同的引用。所以,如果你改变引用的对象。 属性 将在任何被引用的地方发生变化。