그래서 Angular 2 자습서 및 설명서를 진행하고 있습니다. 그것으로 놀고있는 동안, 나는 폼을 그것의 자신의 구성 요소로 분리 할 수 있는지보고 싶었지만 여전히 같은 방식으로 작동합니다. 영웅을 추가하면 자동으로 영웅을 목록에 추가합니다. 부모 구성 요소로 목록이 있고 하위 구성 요소로 양식이 있습니다. 현재 영웅을 추가하면 데이터에 추가되지만 목록은 자동으로 업데이트되지 않습니다. 그러나 대시 보드로 이동 한 다음 목록으로 돌아 가면 영웅이 나타납니다.Angular2 데이터 구성 요소 변경 알림
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroFormComponent } from './hero-form.component';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
templateUrl:'app/heroes.component.html',
styleUrls: ['app/heroes.component.css'],
providers: [HeroService],
directives: [HeroFormComponent]
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;
constructor(private router: Router, private heroService: HeroService) {}
delete(hero: Hero): void {
this.heroService
.delete(hero.id)
.then(() => {
this.heroes = this.heroes.filter(h => h !== hero);
if(this.selectedHero === hero) { this.selectedHero = null; }
});
}
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
this.getHeroes();
}
onSelect(hero: Hero): void {
if(this.selectedHero === hero) {
this.selectedHero = null;
} else {
this.selectedHero = hero;
}
}
gotoDetail(): void {
this.router.navigate(['/detail', this.selectedHero.id]);
}
}
여기 내 양식 구성 요소의 :
여기 내 목록 구성 요소의 무엇이 필요하나요
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
create(name: string): Promise<Hero> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
delete(id: number): Promise<void> {
let url = `${this.heroesUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
getHero(id: number): Promise<Hero> {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
update(hero: Hero): Promise<Hero> {
const url = `${this.heroesUrl}/${hero.id}`;
return this.http
.put(url, JSON.stringify(hero), {headers: this.headers})
.toPromise()
.then(() => hero)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
그렇게 목록 구성 요소가 인식 :
여기import { Component, Injectable } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes.component';
@Component({
selector: 'hero-form',
templateUrl: 'app/hero-form.component.html',
providers: [HeroService]
})
@Injectable()
export class HeroFormComponent {
heroes: Hero[] = [];
constructor(private heroService: HeroService) {}
add(name: string, heroName: HTMLInputElement): void {
name = name.trim();
if (!name) { return; }
this.heroService.create(name)
.then(hero => {
this.heroes.push(hero);
this.selectedHero = null;
});
heroName.value = null;
}
}
내 서비스입니다 데이터를 업데이트하고 실제 목록을 새로 고칩니다.
처음에는 Subject가 정의되지 않음에 대한 오류가 발생하여 서비스에이 가져 오기를 추가하여 정리했습니다. '{subject} from rxjs/Subject'; 목록 페이지에서 결과가 표시되지 않습니다. 그러나 영웅은 대시 보드 페이지에 표시 될 때 목록에 추가됩니다. 목록 페이지에 오류가 없습니다. 목록 페이지에 추가되었지만 제대로 사용하고 있는지 확실하지 않을 수 있습니다. * ngFor = "영웅의 주인공 | 비동기" – Dubster
네, 맞습니다. [AsyncPipe here] (https : //angular.io/docs/ts/latest/api/common/index/AsyncPipe-class.html) –
목록이 지금 비어있는 이유에 대한 통찰력이 있으십니까? – Dubster