ionic 4 native http 在 html 中获取空数据

ionic 4 native http get empty data in html

我是 ionic 4 的初学者。我正在尝试使用本机 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中只使用object他是returnjson回应

 {{object}}

但是如果我想获取标题表单数据 json 我得到的是空页面

 {{object.title}}

这里有几件事。如果你正在使用 angular,并且你想为你的 HTML 代码提供数据,那么你将需要在这个 class 的顶部使用 @component 装饰器。

在该装饰器内部,您将添加一些元数据。此元数据的一部分将是您希望由此组件控制的 html 模板的文件夹引用。您的 html 不知道此 class 中的数据,因为它们没有以 angular 可以理解的任何方式联系在一起。

我会尝试更接近于此的东西:

@Component({
  selector: 'my-page-selector',
  templateUrl: './myPage.component.html',
  styleUrls: ['./myPage.component.css']
})
export class HomePage {

  object : any  ;
  constructor(private http: HTTP) {
   this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
   .then(data => {

    this.object = data.data

  })    .catch(error => this.object = error);
  }
}

然后您将拥有一个 html 文件 'myPage.Component.html',然后可以知道它的驱动组件。

<div>
{{object.title}}
</div>

我会查找 angular 文档并熟悉 angular CLI。这将帮助您一起生成组件和模板,并且可以避免一些混淆。

深入研究一下文档,首先,native http returns 是什么:

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 文档中我发现本机 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)
   });