I am trying to access JSON from angular html template. But it is not returning results. Simply showing Object or error by modification of code.
server.js
response.status(200).json(results.rows);
product.component.ts
export class ProductsComponent implements OnInit {
products = {};
usersJson: any[]=[];
constructor(private service: Service) {
}
ngOnInit(): void {
this.service.getResult().subscribe((data: JSON)=>{
console.log(data);
this.products = data;
this.usersJson = Array.of(data);
console.log(this.products);
})
}
data
data = [
{product_id: 1, product_name:"Phone"},
{product_id: 2, product_name:"laptop"}
]
product.component.html
<p>{{ products}}</p>
<h1>Product</h1>
<p>{{ products[0].product_id}}</p>
<p>{{usersJson[0]}}</p>
<p>{{usersJson[0].product_id}}</p>
Try to use json pipe and '.?' notation to ensure that will not be problems with undefined fields:
<p>{{ products | json }}</p>
<h1> Product </h1>
<p>{{ products[0] != null ? ( products[0]?.product_id | json ) : 'N/A' }}</p>
<p>{{ usersJson[0] != null ? ( usersJson[0] | json ) : 'N/A' }}</p>
<p>{{ usersJson[0]?.product_id }}</p>
NOTE: If product_id is a number/string and not an object, change
( products[0]?.product_id | json )
to
( products[0]?.product_id ) [just delete the json pipe in that line]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.