【发布时间】:2016-09-29 03:11:28
【问题描述】:
我从 angular.io 中找到了一个示例。这个例子与我的应用程序非常相似,具有相同的方法。这个例子使用的是 Promises,但我使用的是 Observables。如果我使用这个示例作为参考,我的应用程序中的所有方法都可以工作,除了服务中的 getHero 方法和 HeroDetailComponent 中的 ngOnInit。所以我想知道是否有人可以帮助并将此方法转换为可观察的,因为我遇到了语法问题。这是我需要转换为 Observable 的代码和plunker
//HeroService
getHero(id: number) { // my id is String
return this.getHeroes()
.then(heroes => heroes.filter(hero => hero.id === id)[0]);
}
//HeroDetailComponent
ngOnInit() {
if (this.routeParams.get('id') !== null) {
let id = +this.routeParams.get('id');
this.navigated = true;
this.heroService.getHero(id)
.then(hero => this.hero = hero);
} else {
this.navigated = false;
this.hero = new Hero();
}
}
所以我想要这样的东西:
//HeroService
public getHero(id: string) {
return this.getHeroes()
.subscribe(heroes => this.heroes.filter(hero => heroes.id === id)[0]); //BTW, what does this [0] mean??
}
编辑:我必须直接检索列表,它不适用于 return this.heroes,如下面的答案中所建议的那样。工作示例:
public getById(id: string) {
//return this.getHeroes() <---- didn't work
return this.http.get('someUrl') // WORKS!
.map(heroes => this.heroes.filter(hero => hero.id === id)[0]);
}
现在我的 ngOnit 仍然有问题,我真的不明白为什么!
ngOnInit(){
let id = this._routeParams.get('id');
this.heroService.getById(id)
//console.log("retrieved id: ",id ) <----- gives correct id!
.subscribe(hero => this.hero = hero);
//console.log("hero: ", this.hero); <----- gives undefined!
}
EDIT2,尝试移动到详细信息页面时仍然不确定:(我认为您的答案中有一个括号,试图查找并找到括号的正确位置?
ngOnInit(){
let id = this._routeParams.get('id');
this.heroService.getById(id)
.subscribe(heroes => {
// this code is executed when the response from the server arrives
this.hero = hero
});
// code here is executed before code from the server arrives
// even though it is written below
}
【问题讨论】: