2016-09-06 7 views
0

그래서 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; 

    } 
} 

내 서비스입니다 데이터를 업데이트하고 실제 목록을 새로 고칩니다.

답변

0

서버에있는 영웅과 클라이언트에있는 영웅을 묶는 것이 아무것도 없으므로 서버의 내용이 변경되면 (양식을 사용하여 추가 할 때) 목록에서 동기화되지 않게됩니다 클라이언트에. getHeroes()를 다시 호출하기 때문에 HeroesComponent로 다시 이동할 때 일시적으로 다시 동기화됩니다. HeroesComponent에 데이터의 변경 사항을 알리는 방법이 필요합니다.

현재 비동기 통신에 대한 약속을 사용하고 있지만 지속적 업데이트가 필요할 때 약속이 완료되었으므로 충분히 좋지 않습니다. 바람직하게는 서비스에서 푸시됩니다. 그것을 위해서는 Observable이 필요합니다. HeroesComponent ngOnInit()에서 서비스 영웅에 옵서버로 등록하고 ngOnDestroy()에서 등록 취소 할 수 있습니다. 이 서비스는 getHeroes()가 호출 될 때 영웅 목록을 보내야하지만 영웅이 추가, 제거 또는 편집 될 때 다시 보내야합니다.

0

문제는

heroes: Subject<Hero[]> = new Subject<Hero[]>(); 

getHeroes(){ 
    this.http.get(this.heroesUrl) 
       .toPromise() 
       .then(response => { 
        this.heroes.next(response.json().data as Hero[]); 
       }) 
       .catch(this.handleError); 
} 

create(name: string): Promise<Hero> { 
    return this.http 
       .post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers}) 
       .toPromise() 
       .then(res => { 
       // update heroes observable 
       this.getHeroes(); 
       return res.json().data 
       }) 
       .catch(this.handleError); 
} 

HeroesComponent는 HTML 템플릿

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

async 파이프를 추가

서비스, 더 이상의 업데이트가 반영되지 않습니다 따라서 영웅을 해결하는 것입니다 약속과 의지를 해결하는 데 도움이 될 것입니다. 향후 업데이트를 위해 목록을 업데이트하십시오.

희망이 도움이됩니다!

+0

처음에는 Subject가 정의되지 않음에 대한 오류가 발생하여 서비스에이 가져 오기를 추가하여 정리했습니다. '{subject} from rxjs/Subject'; 목록 페이지에서 결과가 표시되지 않습니다. 그러나 영웅은 대시 보드 페이지에 표시 될 때 목록에 추가됩니다. 목록 페이지에 오류가 없습니다. 목록 페이지에 추가되었지만 제대로 사용하고 있는지 확실하지 않을 수 있습니다. * ngFor = "영웅의 주인공 | 비동기" – Dubster

+0

네, 맞습니다. [AsyncPipe here] (https : //angular.io/docs/ts/latest/api/common/index/AsyncPipe-class.html) –

+0

목록이 지금 비어있는 이유에 대한 통찰력이 있으십니까? – Dubster

관련 문제