我是 ionic 4 的初学者。我正在尝试使用 native http 从 api 获取 json 数据。我的代码在 json 数据响应下工作正常,但问题是我在 html 中得到了空数据
json
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
主要代码:
import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
object : any ;
constructor(private http: HTTP) {
this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
.then(data => {
this.object = data
}) .catch(error => this.object = error);
}
}
如果我只使用 html 中的对象,他将返回 json 响应
{{object}}
但是如果我想获取标题表单数据 json 我得到的是空页面
{{object.title}}
最佳答案
深入研究一下文档,首先, native http 是什么? 返回是:
this.http.get('http://ionic.io', {}, {})
.then(data => {
console.log(data.status);
console.log(data.data); // data received by server
console.log(data.headers);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
因此,在上述情况下,您的响应位于 data.data
中。你发布的图片让我意识到我们正在处理一个字符串!因此,深入挖掘,在 cordova 文档中,我发现 native http 返回的响应确实是一个字符串!
docs The success function receives a response object with 4 properties: status, data, url, and headers. status is the HTTP response code as numeric value. data is the response from the server as a string. url is the final URL obtained after any redirects as a string. headers is an object with the headers.
所以你需要做的是解析响应!
this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
.then(data => {
this.object = JSON.parse(data.data)
});
关于angular - ionic 4 native http获取html中的空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54486841/