1

I have a json data set with arrays from my ASP.net Core web api, i want to show that data in angular html page. can you help me.

angular 7 cli

home-page.component.ts

 ngOnInit() {

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

  }

Data from web 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
  }

]
Abhishek
  • 1,742
  • 2
  • 14
  • 25
Thevin Malaka.
  • 151
  • 1
  • 7
  • 20

2 Answers2

2

You need to iterate over the items using ngFor

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

also declare the result globally in TS outside ngOnInit.

result : any;

ngOnInit() {
this.serverService.getAllProductData().subscribe(
  (response:Response)=>{ 
    this.result = response;  
    console.log(result); 
  } 
);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

You can use Sajeetharan answer, or try async pipe with auto unsubscribe from the Observable.

public getAllProductData$: Observable<any> = undefined; 

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

and the template:

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

Good luck!

Andrew Radulescu
  • 1,862
  • 13
  • 21