最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在Angular中打印json的特定信息

IT培训 admin 16浏览 0评论

在Angular中打印json的特定信息

在这种情况下,我如何购买产品?我想在ngFor =“ let

中显示该信息

Appponent.ts

export class AppComponent {
  title = 'Bazaar';
  url = '';
  //
  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]);
    })
  }

Appponent.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,却一无所获

回答如下:item.products是json对象,您不能将对象绑定到DOM中。如果要以字符串形式显示对象-使用JSON.stringify

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

在Angular中打印json的特定信息

在这种情况下,我如何购买产品?我想在ngFor =“ let

中显示该信息

Appponent.ts

export class AppComponent {
  title = 'Bazaar';
  url = '';
  //
  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]);
    })
  }

Appponent.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,却一无所获

回答如下:item.products是json对象,您不能将对象绑定到DOM中。如果要以字符串形式显示对象-使用JSON.stringify

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

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论