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

时间:2017-03-29 06:52:52

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

当我正在经历"英雄之旅" 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;
  }
}

从AppModule提供程序数组(全局服务提供程序)注入HeroService

更改&#34; Narco&#34;到&#34; Narcosssss&#34;通过输入:

enter image description here

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

enter image description here

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

1 个答案:

答案 0 :(得分:4)

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