首页 > 解决方案 > 显示从后端返回的对象数据

问题描述

我收到以下格式的对象数据:

import { Istock } from './istock'
import { Dateclose } from './dateclose'

export class Cagr {
    buySell: Istock;
    firstReturn: number;
    sell: Dateclose;
    buy : Dateclose; 
}

这是 istock.ts 文件:

export class Istock {
date: Date;
close: number;
buysell: string;
}

这是 dateclose.ts 文件:

export class Dateclose {
date: Date;
close: number;

}

这是我从控制台日志窗口中打印的服务器获得的格式:

buy: {date: "2019-01-02T00:00:00", close: 156.6423}
buySell: Array(6)
0: {date: "2015-06-02T00:00:00", close: 121.2015, buySell: "Sell"}
1: {date: "2015-06-03T00:00:00", close: 121.3507, buySell: "Sell"}
2: {date: "2015-11-11T00:00:00", close: 109.2406, buySell: "Sell"}
3: {date: "2016-01-22T00:00:00", close: 95.4197, buySell: "Buy"}
4: {date: "2016-01-25T00:00:00", close: 93.5569, buySell: "Buy"}
5: {date: "2016-04-08T00:00:00", close: 102.7861, buySell: "Sell"}
firstReturn: 1.0783205505422155
sell:
    close: 199.9002
    date: "2019-04-30T00:00:00"

这是尝试将值打印到浏览器页面的 html 文件:

<div>
            <mat-list >
                <mat-list-item *ngFor="let item of stockdata ">
                  {{item.buysell.date | date}} {{item.buysell.close | currency}} {{item.buySell.buysell | json}} {{item.firstReturn | json}}
                </mat-list-item>
            </mat-list>
  </div>

我收到此错误:

cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

这是相应的组件文件:

export class DemostockComponent {

 stock: String;
stockdata
public buySellData$: Observable<Cagr[]>

constructor(private api: DemoapiService){}

getStock() {
  this.buySellData$ = this.api.getStock();
  this.buySellData$.subscribe(
           // Use the `data` variable to produce output for the user
           data => {
             this.stockdata = data;
             console.log("data from backend this.stockdata, this.stockdata", this.stockdata);
           }
         )}

}

标签: angular

解决方案


服务器似乎没有返回您期望它返回的内容。根据您的输出,您可能需要更改:

*ngFor="let item of stockdata"

至:

*ngFor="let item of stockdata.buySell"

然后你就可以{{item.date | date}} ...在你的模板中使用。请注意,这与您发布的数据结构不匹配。它应该看起来像这样:

export class Cagr {
    buySell: Istock[];
    firstReturn: number;
    sell: Dateclose;
    buy : Dateclose; 
}

我希望这会有所帮助!


推荐阅读