【问题标题】:How to Parse a Json Data Response from an API call on Ionic as Below如何从 Ionic 上的 API 调用解析 Json 数据响应,如下所示
【发布时间】:2018-06-03 21:30:06
【问题描述】:

我进行了 api 调用并得到如下响应,显示在控制台上

我的 API 提供者:

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

@Injectable()
export class RestapiProvider {

apiUrl = 'http://example.com/api/GetItemByCategory?cat_id=1&merchant_id=1&json=true';

  constructor(public http: HttpClient) {
    //console.log('Hello RestapiProvider Provider');
  }

getItembyCategory() {
     return new Promise(resolve => {
        this.http.get(this.apiUrl).subscribe(data => {
      resolve(data);
      console.log(data);
    }, err => {
        console.log(err);
      });
    });
}

Console.log(data) 显示

[object Object]: {code: 1, details: Object, msg: "success..", request: "{"cat_id":"1","merchant_id":"1","json":"true"}"}

console.log(data)

我需要解析'details: Object'上的json数据

我试过console.log(data.details) 出现错误:

Unable to get property 'details' of undefined or null reference

更新

我试图使用map 运算符,如下所示

this.http.get(this.apiUrl).map(data => data.json()).subscribe(data => {
  resolve(data);
  console.log(data);
}

遇到另一个错误:property json does not exist on type 'Object'

请告诉我如何让它在 ionic 3 上运行。

问候

console.log SS

【问题讨论】:

  • 得不到你想要的?
  • 怎么样:console.log(data.details)
  • 无法获取未定义或空引用的属性“详细信息”

标签: json angular ionic-framework


【解决方案1】:

你为什么不试试这样:

导入 toPromise 操作符:

import 'rxjs/add/operator/toPromise';

然后在它的帮助下将你的 observable 变成一个 Promise。当您使用新的 Angular HttpClient 时,无需将响应映射到 Json,默认情况下已映射。

getItembyCategory() {
 return this.http.get(this.apiUrl)
  .toPromise()
  .then((data: any) => {
     console.log('Success', data.details);
     return data;
  })
  .catch(err => {
     console.log('Error', err);
     return err;
  })
}

这样代码就干净多了。它已经过测试并且可以工作。如果没有,那么您应该检查您的 apiUrl。

已编辑

您收到错误property 'details' does not exist on type 'Object' 的原因是您需要为收到的数据对象指定一个类型(默认的Object 除外)。我用这个更新了这个例子:

(data: any) => {
  console.log(data.details);
  return data;
}

这比data['details'] 中丑陋的方括号要好得多:)。

【讨论】:

  • 是的,代码有效。它返回 json 对象,如上图所示。问题是如何解析“详细信息”内的嵌套 json 对象或数组?我试过console.log(data.details)。它返回错误:“对象”类型上不存在属性“详细信息”
【解决方案2】:

我设法通过“详细信息”

data['details'];

和“项目”

data['details']['item'];

感谢所有建议。

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2012-10-31
    • 2019-02-27
    • 1970-01-01
    • 2019-02-17
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多