简体   繁体   English

访问 Json Object 使用 angular ZFC35FDC70D5FC69D269883A8E 模板从快速 js 返回

[英]Access Json Object return from express js with angular html template

I am trying to access JSON from angular html template.我正在尝试从 angular html 模板访问 JSON 。 But it is not returning results.但它没有返回结果。 Simply showing Object or error by modification of code.通过修改代码简单地显示 Object 或错误。

server.js服务器.js

response.status(200).json(results.rows);

product.component.ts 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 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 '.?'尝试使用json pipe和 '.?' 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注意:如果 product_id 是数字/字符串而不是 object,请更改

( products[0]?.product_id | json ) 

to

( products[0]?.product_id )  [just delete the json pipe in that line]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM