【问题标题】:Angular 5 HTTPclient json errorAngular 5 HTTPclient json错误
【发布时间】:2018-04-18 15:22:14
【问题描述】:

我正在尝试从我的 Angular 5 离子项目中的 json 文件导入数据,但我不能,因为我收到错误: TS2339:属性结果不存在于 home.ts 中的类型“对象”(其中 2 个)

提供者:people.ts

  getPeople() {
    return this.http.get('http://www.json-generator.com/api/json/get/cghlMAGJvm?indent=10')
  }
}

home.ts

  constructor(public navCtrl: NavController,
              public service: People)
  {
    this.service.getPeople()

      .subscribe(
        data => this.people = data.results
      )
  }

  toggleReorder(){
    this.shouldReorder = !this.shouldReorder
  }
doRefresh(e){
this.service.getPeople()
  .subscribe(
    data => this.people.unshift(...data.results),
    err => console.log(err),
    () => e.complete()
  )
}
}

正如我在 angular/http 指南中看到的那样:

showConfig() {
  this.configService.getConfig()
    .subscribe(data => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    });
}

但我想复制所有数据而不是只复制几个部分。正确的做法是什么?

【问题讨论】:

  • 在浏览器中也出现错误:错误错误:未捕获(承诺中):TypeError:this.service.getPeople(...).subscribe不是函数TypeError:this.service.getPeople(。 ..).subscribe 不是函数
  • 请给minimal reproducible example。另外,我建议您阅读angular.io/guide/http
  • 我只复制了“结果”所在的部分。 “结果”这个词出现了两次,并写了另一个我在浏览器上看到的错误。两者都在我的代码中。不多也不少。是的,我看到了 angular 的 http 指南,一切都做对了。
  • 你没有做对所有事情,你没有输入任何东西。因此编译器的抱怨。
  • 你能告诉我我要做什么吗?

标签: angular ionic-framework angular5


【解决方案1】:

在您的 people.ts 上添加地图运算符的导入。

import 'rxjs/add/operator/map';


getPeople() {
    return this.http.get('http://www.json-generator.com/api/json/get/cghlMAGJvm?indent=10').map(res => res.json());
}

http://www.json-generator.com/api/json/get/cghlMAGJvm?indent=10 给出的响应已经是结果,所以不需要添加data.results,响应中不存在该属性。

this.service.getPeople().subscribe( data => {
    this.people = data
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2018-06-03
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多