[英]Angular 2 Two-way Binding updates mock service constant
As I was going through the "Tour of Heroes" Angular 2 tutorial, I have noticed that when ngModel
changes, the change propagates to other components utilizing the same object. 在我学习《英雄之旅》 Angular 2教程时,我注意到当ngModel
更改时,更改传播到使用同一对象的其他组件。 But when I tried to log the mock service constant HEROES
on the console, its value also changed. 但是,当我尝试在控制台上记录模拟服务常量HEROES
时,其值也发生了变化。
mock-heroes.ts 模拟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 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 英雄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 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 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;
}
}
The HeroService
is injected from the AppModule providers array (global service provider). HeroService
是从AppModule提供程序数组(全局服务提供程序)中注入的。
Changing the name from "Narco" to "Narcosssss" through the input: 通过输入将名称从“ Narco”更改为“ Narcosssss”:
updates the constant HEROES
as seen on the console: 更新控制台上显示的常量HEROES
:
Can someone please explain to me how it works? 有人可以告诉我它是如何工作的吗?
Your hero
objects have the same reference throughout your app. 您的hero
对象在整个应用程序中具有相同的引用 。 So, if you change the referenced object. 因此,如果您更改引用的对象。 The property will change wherever it's been referenced. 该属性将在被引用的任何地方更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.