【问题标题】:Ionic Angular displaying and parsing JSON data from APIIonic Angular 显示和解析来自 API 的 JSON 数据
【发布时间】:2020-04-01 14:19:50
【问题描述】:

我有这些来自我们 API 的示例 JSON 数据格式

{
    "type": "BasicResponse",
    "name": "",
    "serverId": "",
    "requestId": "",
    "output": {
      "Result": {
        "ListSequence": [
          {
            "status": "ORDER PROCESSED",
            "date": "",
            "comment3": "",
            "comment4": "",
            "comment1": "",
            "time": "",
            "comment2": ""
          },
        ],
        "RESULT": "SUCCESS"
      }
    },
    "status": {
      "success": true,
      "returnCode": 0
    }
  }

我只想显示所有状态的值(例如 ORDER PROCESSED),到目前为止它在我的 html 页面中显示如下。顺便说一句,我关注了这个guide

这是我的页面.ts

constructor(private dataService: DataService, private http: HttpClient) {
  this.data = '';
  this.error = '';
 }

 private prepareDataRequest(): Observable<object> {
  // Define the data URL
  const dataUrl = '';
  // Prepare the request
  return this.http.get(dataUrl);
}

ionViewWillEnter() {
  // Load the data
  this.prepareDataRequest()
    .subscribe(
      data => {
        // Set the data to display in the template
        this.data = JSON.stringify(data);
      },
      err => {
        // Set the error information to display in the template
        this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
      }
    );
}

这是我的页面.html

<p *ngIf="!error;else errorContent">{{ data ? data : '-' }}</p>
  <ng-template #errorContent><p><span style="color: red;">{{error}}</span></p></ng-template>

【问题讨论】:

  • 您应该遵循另一个指南。有很多方法可以从 api 获取数据。这个我没见过。

标签: angular typescript ionic-framework


【解决方案1】:

JSON.stringify 与您在这里实际需要的相反。我假设您希望通过“仅所有状态”显示 status 数组中所有元素的 ListSequence 属性。如果是,那么所有状态都可以直接使用.map()提取到它自己的数组中并显示出来。试试下面的

public statuses = [];

private prepareDataRequest(): Observable<any> {  // <-- change return type here
  // Define the data URL
  const dataUrl = '';
  // Prepare the request
  return this.http.get(dataUrl);
}

ionViewWillEnter() {
  // Load the data
  this.prepareDataRequest().subscribe(
    data => {
      // Set the data to display in the template
      this.statuses = data.output.Result.ListSequence
        .map(item => {
          console.log('item.status: ', item.status);   // <-- log the `status` here
          if (item.status && item.status !== '') {
            return item.status;
          } else {
            return '-';
          }
        });    // <-- add closing bracket here
    },
    err => {
      // Set the error information to display in the template
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

模板

<ng-container *ngIf="!error; else errorContent">
  <p *ngFor="let status of statuses">
    {{ status }}
  </p>
</ng-container>
<ng-template #errorContent>
  <p>
    <span style="color: red;">{{error}}</span>
  </p>
</ng-template>

【讨论】:

  • 我收到“'object'类型的属性'输出'不存在”
  • 我已经更新了答案。请看一看。您可以将prepareDataRequest() 函数的返回类型从Observable&lt;object&gt; 更改为Observable&lt;any&gt;。当我们不传递头信息时,假定返回类型是不好的。另一个好的做法是在服务中使用prepareDataRequest() 函数并将服务注入到您希望使用它的组件中。
  • 我还得到:')' 预期来自 '};",我很难调试它
  • 那是我的错。我忽略了正确关闭.map() 方法。请查看我的更新答案。
  • 那么您能否在地图的开头添加一个日志来检查status 属性的实际值是多少?请在此处将输出作为图像发布。我已经编辑了代码。
【解决方案2】:

要遍历所有状态,请使用*ngFor 指令。在 Component.html 中添加以下代码:

<div *ngFor="let result of data?.output?.Result?.ListSequence">
        <p> {{ result.status }} </p>
   </div>

这是工作示例:Working demo

或者,为了更简洁的代码,在component.ts 文件中声明一个变量并为其分配ListSequence 值。

公开resultArray :any[] = [];

protected someMethod(){
    ...
   this.resultArray = data.output.Result.ListSequence;
....
}

然后在component.html文件中你可以使用如下列表:

<div *ngFor="let result of resultArray">
        <p> {{ result.status }} </p>
   </div>

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多