将元素添加到 Observable 数组打字稿

问题描述 投票:0回答:1

我有一个 Angular 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() 返回的英雄添加到 Heroes Observable 中。我该怎么做?

angular typescript rxjs
1个回答
5
投票

heroService.getHeroes()
返回的 Observable 分配给
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 来进行进一步的改进,但这是一个好的开始。

© www.soinside.com 2019 - 2024. All rights reserved.