类型“对象”上不存在属性“过滤器”。尝试过滤响应时

时间:2018-11-26 16:35:42

标签: html angular typescript http

我正在尝试从json文件中获取与网址中播放器名称相同的数据。例如:localhost:4200 / players / Febiven应该只返回有关Febiven的信息。我正在使用Angular 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)
  }

player-info.component.ts

 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
      })
    });

在类型“对象”上不存在错误“属性”过滤器。我真的不知道如何解决这个问题,我看了多个答案,但似乎没有一个对我有用。如果有人可以帮助我解决此错误,那就太好了

谢谢

2 个答案:

答案 0 :(得分:0)

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)
}

答案 1 :(得分:0)

尝试一下,它将起作用: 在类中定义一个参数,并在ngOnInit()函数中使用它,如下所示:

export class VideoDetailComponent implements OnInit, OnDestroy {
  data_new:any;
  
  ngOnInit() {
    this.http.get("assets/json/videos.json").subscribe(data =>{
        this.data_new = data;
          this.data_new.filter(item=>{
            console.log(item)
            // do your work here
          })

      })
      }
}