简体   繁体   English

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

[英]Property 'filter' does not exist on type 'Object'. When trying to filter response

Im trying to get data from a json file that equal the name of the player in the url. 我试图从json文件中获取与网址中播放器名称相同的数据。 For example: localhost:4200/players/Febiven should only return the information about Febiven. 例如:localhost:4200 / players / Febiven应该只返回有关Febiven的信息。 Im using Angular 6 我正在使用Angular 6

So far I have this code: 到目前为止,我有以下代码:

player.service.ts 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 玩家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
      })
    });

Im getting the error 'Property 'filter' does not exist on type 'Object'. 我收到错误消息“属性”过滤器,类型“对象”不存在。 And I don't really have an idea how to fix this, I looked at multiple answers, but none seemed to work for me. 我真的不知道如何解决这个问题,我看了多个答案,但似乎没有一个对我有用。 If someone could help me with fixing this error thatd be great 如果有人可以帮助我解决此错误,那就太好了

Thanks 谢谢

filter only exists on arrays. filter仅存在于阵列上。 Your response is an object. 您的回应是一个对象。 You can do this instead: 您可以改为:

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

Try this it will work: define a parameter inside your class & use it in ngOnInit() function like this: 尝试一下,它将起作用:在类中定义一个参数,并在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 }) }) } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM