angular - ionic 4 native http获取html中的空数据

标签 angular native ionic4

我是 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}}

enter image description here

但是如果我想获取标题表单数据 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/

相关文章:

angular - 通过映射将类型(接口(interface))转换为可观察的

Angular 2 : Swapping between different components without destroying them

angular - 访问 angular 2 组件中的 bootstrap scss 变量

c - C++CLI 中的 System.ExecutionEngineException

java - 如何在hql上使用 'group by'?

Angular 4获取dom元素

java - 如何在 SWT ColorDialog 中预加载自定义颜色

angular - Ionic 4 无法显示手机拍摄的照片

angular - ionic slider 隐藏最后一张幻灯片中的下一个按钮 ionic 4

javascript - 实现相机插件后无法再打开相机页面