I've created an Angular 2 component that utilizes a service to fetch data from a 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()
);
}
}
Is there a more efficient way to improve the addHero function? Currently, it seems inefficient. I want to simply add the returned hero from this.heroService.addHero() to the heroes observable. How can I achieve this?