62

看起来 HTML 中的货运变量有问题:

app/freightList.component.html:13:8 中的错误尝试区分“[object Object]”时出错

下面是代码

freight.service.ts
=======================

    getFreight (): Promise<Freight[]> {
        return this.http.get(this.freightUrl)
                  .toPromise()
                  .then(this.extractData)
                  .catch(this.handleError);
    }

  private extractData(res: Response) {
      let body = res.json();
      return body || { };
  }

freightList.component.ts
========================
    getFreight() {
        this.freightService
            .getFreight()
            .then(freight => this.freight = freight)
            .catch(error => this.error = error); // TODO: Display error message
    }

freightList.component.html
============================

       <tr *ngFor="let frght of freight">
       <td>{{frght.grp}} - {{frght.grpname}}</td>
       <td>{{frght.subgrp}} - {{frght.subgrpname}}</td>
       <td>{{frght.prodno}} - {{frght.prodname}}</td>
       <td>{{frght.percent}}</td>
       <td>{{frght.effective_date}}</td>
       <td><button (click)="deleteFreight(frght, $event)" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-remove"></span> Remove</button></td>
       <td><button (click)="editFreight(frght)" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
       </tr>

Response body
==================

    [{
        "effective_date": "01/01/2016",
        "grp": "01",
        "grpname": "STOPS/FLEX HOSES/COVER PLATES",
        "id": "1",
        "percent": "10",
        "prodname": "DWV PVC PIPE 100MM X 6MTR SN6  SWJ",
        "prodno": "1400200",
        "subgrp": "02",
        "subgrpname": "DWV PIPE - UP TO 150MM"
    }, {
        "effective_date": "01/02/2016",
        "grp": "01",
        "grpname": "STOPS/FLEX HOSES/COVER PLATES",
        "id": "2",
        "percent": "11",
        "prodname": "PVC PIPE    100MM X 6MTR SWJ SN10",
        "prodno": "1400201",
        "subgrp": "03",
        "subgrpname": "DIMPLEX BATHROOM ACCESSORIES"
    }]
4

4 回答 4

110

您的 extractData(可能还有您的 HTTP API)正在返回一个对象 {} - ngFor 需要一个数组 [] 来迭代。

更改您的服务/API 以生成数组,或转换组件中的对象。

于 2016-08-24T23:25:09.687 回答
3

(对我而言)问题出在我的 newState 定义中。下面是正确的定义:

const newState = (state, newData) => {
    return Object.assign([], state, newData);
}

我的 newState 正在将我的数组转换为一个对象,因为我使用了错误的括号 - 错误的方式如下。

const newState = (state, newData) => {
    return Object.assign({}, state, newData);
}

祝你好运,我希望这会有所帮助,罗布

于 2020-01-28T03:24:00.570 回答
1

当我更改我调用的 WebApi 以返回 aTask<IActionResult>而不是以前的IEnumerable<object>. 检查响应是否包含在对象中。我不得不将我的 extractData 方法更改为:

private extractData(res: Response) {
   let body = res.json();
   return body.result || body || { };
}
于 2018-02-02T11:33:36.273 回答
-3

最好的方法是获取NgForm对象并调用其reset()函数。

例子:

html文件

<form #exampleform='ngForm'>

</form>

ts文件

@ViewChild('exampleform') exampleform :NgForm;

this.exampleform.reset(); // resets the form
于 2018-03-04T01:43:43.530 回答