我试图从一个json文件中获取数据,该文件等于url中播放器的名称。例如:localhost:4200/players/febiven应该只返回关于febiven的信息。IM使用角度6
到目前为止,我有这个代码:
player.service.ts播放器
get(ingameName){
return <Observable<Player>> this.http.get(endpoint).map(response =>{
let data = response.filter(item=>{
if (item.ingameName == ingameName) {
return item
}
});
if (data.length == 1){
return data[0]
}
return {}
})
.catch(this.handleError)
}
private handleError(error:any, caught:any): any{
console.log(error, caught)
}
播放器信息组件
export interface Player {
ingameName: string;
name: string;
intro: string;
image: string;
info: string;
team: string;
dob: string;
earnings: string;
role: string;
game: string;
favourite: string;
IDs: string;
}
export class PlayerInfoComponent implements OnInit {
players: Player[] = null;
private routeSub:any;
private req:any;
ingameName:string;
player : player;
constructor(private route: ActivatedRoute, private plService : PlayerService) { }
ngOnInit() {
this.routeSub = this.route.params.subscribe(params => {
this.ingameName = params['ingameName'];
this.req = this.plService.get(this.ingameName).subscribe(data=>{
this.player = data as player
})
});
获取错误“property”filter的IM在类型“object”上不存在。我真的不知道如何解决这个问题,我看了很多答案,但似乎没有一个对我有用。如果有人能帮我纠正这个错误那就太好了
谢谢
最佳答案
filter
仅存在于数组中。你的反应是个目标。你可以这样做:
get(ingameName){
return <Observable<Player>> this.http.get(endpoint).map(response =>{
let data = response.json();
if (data.ingameName == ingameName){
return data;
}
return {};
})
.catch(this.handleError)
}