首页 > 解决方案 > 在 Angular 中打印 json 的特定信息

问题描述

在这种情况下,我如何访问产品?我想在 ngFor="let 中显示该信息

应用组件.ts

export class AppComponent {
  title = 'Bazaar';
  url = 'https://api.hypixel.net/skyblock/bazaar';
  //
  items = [];

  constructor(private json: JsonService) {
    this.json.getJson(this.url).subscribe((res: any) => {
      console.log(res);

      for(let key in res)
      if(res.hasOwnProperty(key))
        this.items.push(res[key]);
    })
  }

App.component.html

<div *ngFor="let item of items">{{item}}</div>

这是 Json 结构:

{
  "success": true,
  "lastUpdated": 1588676089955,
  "products": {
    "INK_SACK:3": {
      "product_id": "INK_SACK:3",
      "sell_summary": [
        {
          "amount": 5643,
          "pricePerUnit": 5.2,
          "orders": 1
        },
      ],
      "buy_summary": [
        {
          "amount": 63182,
          "pricePerUnit": 6.6,
          "orders": 2
        },
       ],

json.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class JsonService {

  constructor(private http: HttpClient) { }

  getJson(url: string){
    return this.http.get(url);
  }
}

我已经在 HTML 中尝试过 item.products 并且一无所获

标签: node.jsjsonangularxmlhttprequest

解决方案


item.products是一个 json 对象,你不能将一个对象绑定到 DOM 中。如果您想将对象呈现为字符串 - 使用JSON.stringify

<div *ngFor="let item of items">{{JSON.stringify(item.products)}}</div> 

推荐阅读