1

我有一个 json 数据集,其中包含来自我的 ASP.net Core Web api 的数组,我想在 Angular html 页面中显示该数据。你能帮助我吗。

角度 7 cli

主页.component.ts

 ngOnInit() {

    this.serverService.getAllProductData().subscribe(
      (response:Response)=>{ 
        let result = response;  
        console.log(result); 
      } 
    );

  }

来自网络 API 的数据

[

  {
    "productId": 1,
    "productName": "product 1",
    "productPrice": 500
  },

  {
    "productId": 2,
    "productName": "product 2",
    "productPrice": 1000
  },

  {
    "productId": 3,
    "productName": "product 3",
    "productPrice": 2000
  },

  {
    "productId": 4,
    "productName": "PRODUCT 4",
    "productPrice": 3000
  },

  {
    "productId": 5,
    "productName": "produt 5",
    "productPrice": 10000
  }

]
4

2 回答 2

2

您需要使用 ngFor 迭代项目

 <ul>
    <li *ngFor="let resultObj of result">
      {{ resultObj.productName}}
    </li>
 </ul>

还在 ngOnInit 之外的 TS 中全局声明结果。

result : any;

ngOnInit() {
this.serverService.getAllProductData().subscribe(
  (response:Response)=>{ 
    this.result = response;  
    console.log(result); 
  } 
);
}
于 2019-04-17T14:12:38.537 回答
0

您可以使用 Sajeetharan 答案,或者尝试async使用可观察对象自动取消订阅的管道。

public getAllProductData$: Observable<any> = undefined; 

ngOnInit() {
    this.getAllProductData$ = this.serverService.getAllProductData();
}

和模板:

<div *ngIf="(getAllProductData$ | async) as data">
   <ul>
     <li *ngFor="let item of data">
       {{ item.productName}}
     </li>
  </ul>
</div>

祝你好运!

于 2019-04-17T14:43:35.250 回答