将元素添加到Observable数组typescript

时间:2016-08-26 15:21:08

标签: angular typescript rxjs

我有一个角度2组件,它利用从rest api获取数据的服务。

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 个答案:

答案 0 :(得分: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来进一步改进,但这是一个良好的开端。