【问题标题】:Print specific information of a json in Angular在 Angular 中打印 json 的特定信息
【发布时间】:2020-08-20 01:10:12
【问题描述】:

在这种情况下,我如何访问产品?我想在 ngFor="let

中显示该信息

App.component.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,但一无所获

【问题讨论】:

  • 用它来格式化你的 json jsonformatter.org 并展示你的 json mayebe 一个对象的小例子,因为这个图像不可读
  • 你必须展示你已经尝试过的东西。如果没有看到您尝试使用的代码,我们无法理解为什么它对您不起作用。
  • 这是所有代码,不再赘述。我可以在 console.log 中显示信息,但在屏幕上没有打印
  • '我已经在 HTML 中尝试了 item.products,但一无所获' - 向我们展示 HTML 代码。
  • {{item.products}}

标签: node.js json angular xmlhttprequest


【解决方案1】:

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

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

【讨论】:

  • TypeError:无法读取未定义的属性“字符串化”。我要研究stringify
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
相关资源
最近更新 更多