我从angular.io中找到了一个示例。这个例子与我的应用非常相似,使用了相同的方法。这个例子使用Promises,但我使用Observables。如果我使用这个例子作为参考,除了服务中的getHero方法和HeroDetailComponent中的ngOnInit之外,我已经在我的应用中使用了每种方法。所以我想知道是否有人可以帮助并将此方法转换为可观察的,因为我在语法上遇到了问题。这是我需要转换为可观察的代码和plunkerHTTP:Angular 2 + TS如何在HTTP中使用Observables
//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??
}
编辑:我不得不居然直接检索列表,它不与工作按照以下答案中的建议返回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
}
谢谢! getHero就像一个魅力,但现在我在我的ngOnInit有一个(奇怪的?)错误。你能帮我吗?更新了我的问题! – Alex
我更新了我的答案。 –
非常好的解释,谢谢!我一般都不熟悉编码,我记得我在某个地方遇到过,这是Promise和Observables之间的区别之一。但我想我忘了它!再次更新问题,因为我正在移动的详细信息页面仍然抱怨它未定义!我想你有一个支架太多,或太少,我试图把括号放在他们的正确位置,但我想这仍然是错误的? – Alex