Json 离子API未定义

Json 离子API未定义,json,angular,api,ionic-framework,Json,Angular,Api,Ionic Framework,我有一款带有科尔多瓦的爱奥尼亚应用程序。我只想从URL获取JSON 我创建了一个服务调用rest.service.ts rest.service.ts 在这个文件中,我可以看到信息。如果我插入像 console.log(JSON.parse(answer.data)) 我可以在JSON中看到我想要的结果。 问题是当我尝试在其他文件中使用此方法时 otherpage.page.ts 这里此。项目。。。是未定义的发生了什么事?我尝试了平台。准备好了,插入ngOnInit。。。没有任何功能。您需要修改

我有一款带有科尔多瓦的爱奥尼亚应用程序。我只想从URL获取JSON

我创建了一个服务调用
rest.service.ts

rest.service.ts

在这个文件中,我可以看到信息。如果我插入像

console.log(JSON.parse(answer.data))

我可以在JSON中看到我想要的结果。

问题是当我尝试在其他文件中使用此方法时

otherpage.page.ts


这里<代码>此。项目
。。。是未定义的发生了什么事?我尝试了
平台。准备好了
,插入
ngOnInit
。。。没有任何功能。

您需要修改服务并在您的页面上订阅此服务

 BASE_URL = 'http://whatever.....';
 getProjects() {
    const URL = this.BASE_URL + 'getProjects';
    return this.http.get(URL, {}, { 'Content-Type': 'application/json' });
  }
订阅此服务可在您的page.ts文件中看到

this.rest.getProjects().subscribe((answer)=>{
    this.projects = JSON.parse(answer.data);
    console.log(this.projects); // here you get the json 
},error=>{
    consoole.log(error)
});
注:

console.log(this.projects);//未定义 因为这一行在http observable发送响应之前执行,所以您需要订阅该http observable以获取json


谢谢你。只有subscribe()方法不存在。我用了。然后()。我只是想尽可能简化我的page.ts文件,所以我没有考虑这个问题。我只是想在我的Rest文件中完成所有API工作。但它现在工作得很好!谢谢
 BASE_URL = 'http://whatever.....';
 getProjects() {
    const URL = this.BASE_URL + 'getProjects';
    return this.http.get(URL, {}, { 'Content-Type': 'application/json' });
  }
this.rest.getProjects().subscribe((answer)=>{
    this.projects = JSON.parse(answer.data);
    console.log(this.projects); // here you get the json 
},error=>{
    consoole.log(error)
});