2017-10-10 29 views
1

我是TypeScript和Angular的初学者,所以这个问题可能会有些奇怪。 我有一个简单的JSON返回英雄的名单: http://demo8521374.mockable.io/titanAngular observable不过滤json数组的结果

我需要我的服务进行GetById但为什么总是英雄出来不确定的,可有人请点我到正确的位置,这是什么我这样做的:

 return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => { 
 
      var result = response.json().heroes as Hero[]; 
 
      console.log(result); 
 
      return result; 
 
     }).filter(x => x.filter(x => x.id == id)).first().toPromise();

在我的控制台I可以看到阵列印刷但在我的成分没有得到对象:

ngOnInit(): void { 
 
     this.route.paramMap 
 
      .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id'))) 
 
      .subscribe(hero => this.hero = hero); 
 

 
     console.log(this.hero) 
 
    }

谢谢!

回答

1

修改了代码如下,它的工作,肯定有一个更好的办法:

getHero(id: number): Promise<Hero> { 
 

 
     return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => { 
 
      var result = response.json().heroes as Hero[]; 
 
      console.log(result); 
 
      return result; 
 
     }) 
 

 
      .map(heros => { 
 
       let y = heros.filter(x => x.id == id)[0] 
 
       console.log(y); 
 
       return y; 
 
      }) 
 
      .toPromise();

+0

这是一种方法。 'Observable.filter()'正在过滤_events_(!),而不是事件中的数据。因此,在.map()中使用'.filter()'在这里是绝对正确的。 –

0

虽然switchMap返回一个新的可观察值,我假设getHero方法也返回一个可观察值。在这种情况下,你需要订阅getHero观察到现在的switchMap观察到的分配给你的英雄属性,如下所示:

ngOnInit(): void { 
     this.route.paramMap 
      .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')) 
      .subscribe(hero => this.hero = hero)); 

     console.log(this.hero) 
    } 

或者,如果getHero返回一个承诺,那么它应该如下所示:

ngOnInit(): void { 
     this.route.paramMap 
      .do((params: ParamMap) => this.heroService.getHero(+params.get('id')) 
      .then(hero => this.hero = hero)).subscribe(); 

     console.log(this.hero) 
    } 

虽然你所做的事情有点不清楚,并且似乎表明你正在混合Observables和Promises,但我猜测你只需要Observables就很难禁止这个问题的答案。

更新服务:

return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => { 
      var result = response.json().heroes as Hero[]; 
      console.log(result); 
      return result; 
     }).filter(x => x.id === id).first().toPromise(); 
+0

感谢,但没有帮助,问题是在服务而不是组件,当我手动创建一个英雄承诺,并从它的工作返回它。 – TomerMiz

+0

@TomerMiz查看更新的答案。它看起来像你的过滤器是错误的。您传递给过滤器方法的谓词将针对数组中的每个项目运行一次。看起来好像你将数组中的每个项目当作一个数组本身。 – peinearydevelopment