我从angular.io找到了一个例子。这个示例与我的应用程序非常相似,使用的是相同的方法。这个例子使用的是Promises,但是我使用的是Observables。如果以本示例作为参考,则除了服务中的getHero方法和HeroDetailComponent中的ngOnInit之外,我的应用程序中都可以使用所有方法。所以我想知道是否有人可以帮助将这种方法转换为可观察的方法,因为我在语法上遇到了麻烦。这是我需要转换为Observable和the 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??
}
编辑:我实际上必须直接检索列表,它不能与返回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
}
如果你调用subscribe()
上的Observable
一个Subscription
被返回。您无法致电subscribe()
订阅。
而是只使用一个运算符(map()
)并subscribe()
在呼叫站点上使用:
public getHero(id: string) {
return this.getHeroes()
.map(heroes => this.heroes.filter(hero => heroes.id === id)[0]);
}
ngOnInit(){
let id = this._routeParams.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
与此相反subscribe()
,map()
也会对进行运算,Observable
但还会返回Observable
。
[0]
表示只接受筛选出的英雄中的第一项。
更新
ngOnInit(){
let id = this._routeParams.get('id');
this._searchService.getById(id)
.subscribe(searchCase => {
// this code is executed when the response from the server arrives
this.searchCase = searchCase;
console.log("id: ", this.searchCase);
});
// code here is executed before code from the server arrives
// event though it is written below
}
该代码是一个功能
searchCase => {
// this code is executed when the response from the server arrives
this.searchCase = searchCase);
console.log("id: ", this.searchCase);
}
传递给,subscribe()
并在Observable
有订阅者的新数据时调用此函数。因此,此代码不会立即执行,而仅在可观察对象发出新数据时才执行。
之后的代码将subscribe()
立即执行,因此在上述功能之前执行,因此this.searchCase
尚无值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句