2016-08-26 4 views
2

나머지 api에서 데이터를 가져 오는 서비스를 사용하는 각도 2 구성 요소가 있습니다.관찰 가능한 배열에 요소 추가 typescript

import { OnInit, Component } from '@angular/core'; 
import { Hero } from './hero'; 
import { HeroService } from './hero.service2'; 
import { Observable } from 'rxjs'; 


@Component({ 
    selector: 'my-list', 
    templateUrl: 'app/hero-list.component.html', 
}) 
export class HeroListComponent implements OnInit { 
    errorMessage: string; 
    heroes: Observable<Hero[]>; 
    mode = 'Observable'; 

    constructor (
     private heroService: HeroService 
) {} 

    ngOnInit() { this.getHeroes(); } 

    getHeroes() { 
    this.heroes = this.heroService.getHeroes() 
    } 

    addHero (name: string) { 
    if (!name) { return; } 

    this.heroService.addHero(name) 
        .subscribe(
         hero => this.getHeroes() 
        ); 
    } 
} 

addHero를 개선하려면 어떻게해야합니까? 왜냐하면 지금은 매우 비효율적 인 것처럼 보입니다. Observable 영웅에게 this.heroService.addHero()가 반환 한 영웅을 추가하고 싶습니다. 어떻게해야합니까?

답변

1

hereoes 속성으로 돌아가는 Observable을 지정하고 영웅을 추가 할 때마다 다시 할당해도 아무런 의미가 없습니다.

heroes: Hero[]; 

    ngOnInit() { 
    this.getHeroes(); 
    } 

    getHeroes() { 
    this.heroService.getHeroes().subscribe(heroArray => { 
     //The response from getHeroes() is a array of Hero so assign 
     // that directly to heroes property 
     this.heroes = heroArray; 
    }); 
    } 

    addHero (name: string) { 
    //Makes sure name isn't an empty string. Typescript compiler will catch everything else. 
    if (name) { 
     this.heroService.addHero(name).subscribe(hero => { 
     //I assume the response from the addHero Observable is a Hero object 
     this.heroes.push(hero); 
     }); 
    } else { 
     //Notify console when passed empty string. 
     console.error('Error! addHero was passed an empty string!'); 
    } 
    } 

당신은 아마 당신의 HeroService을 편집하여 더 개선 할 수 있지만, 이것은 좋은 시작이다 :

HeroService을 편집하지 않고, 그렇게 같은 HeroListComponent을 향상시킬 수 있습니다.

관련 문제