2016-08-26 69 views
2

我有一個角度2組件,它利用從其他api獲取數據的服務。將元素添加到Observable數組打字稿

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?因爲現在看起來效率很低。我只想將this.heroService.addHero()返回的英雄添加到英雄Observable中。我怎麼做?

回答

1

將Observable分配給heroService.getHeroes()返回hereoes屬性沒有意義,並且每次添加Hero時重新分配它也沒有多大意義。

沒有編輯HeroService,可以提高HeroListComponent像這樣:

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進一步改進,但這是一個好的開始。