Angular - 无法使用* ngFor在HTML页面中打印json数据

问题描述 投票:1回答:3

我是棱角分明的新手。我创建了一个服务类,它以json格式返回产品详细信息。

api.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ApiService {

  constructor(private http: Http) { }

  fetchData() {
    return this.http.get('http://funiks.com/qbook/api/productmasterjson.php').map(
        (response) => response.json()
      ).subscribe(
        (data) => data
      )
  }
}

现在我在组件类api.component.ts中调用了这个服务

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';


@Component({
  selector: 'app-api',
  templateUrl: './api.component.html',
  styleUrls: ['./api.component.css']
})
export class ApiComponent implements OnInit {

  public details;

  constructor(private api:ApiService) { }

  ngOnInit() {
    this.details = this.api.fetchData();
    console.log(this.details);
  }

}

现在我想在HTML页面中打印所有数据。这是我试图打印json数据

<tr *ngFor="let d of details">
      <td>{{d.CATEGORY}}</td>
      <td>{{d.HSN}}</td>
      <td>{{d.ID}}</td>
      <td>{{d.NAME}}</td>
      <td>{{d.POSTINGHEAD}}</td>
      <td>{{d.PRODUCTSERVICE}}</td>
      <td>{{d.RATE}}</td>
      <td>{{d.SACCODE}}</td>
      <td>{{d.TAX_CONNECTED}}</td>
      <td>{{d.TYPE}}</td>
      <td>{{d.UNIT}}</td>
    </tr>

但不幸的是它抛出错误和错误就像

错误错误:无法找到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。

json angular
3个回答
0
投票
  1. 你的组件不知道fetchData的类型,你应该用 fetchData():Observable<Product[]> { 键入它
  2. 您不应该订阅fetchData()中的观察点,只需返回可观察量即可 fetchData():Observable<Product[]> { return this.http.get('http://funiks.com/qbook/api/productmasterjson.php') .map((response) => response.json() ) }
  3. 在您的组件中,订阅observable并输入details details: Product[]; ngOnInit() { this.api.fetchData().subscribe(data => this.details = data); console.log(this.details); }

0
投票

首先需要将public details声明为数组

public details: any[];

在异步请求返回任何内容之前,除非您指定,否则模板对details的数据类型一无所知。 我想这就是你得到这样的错误的原因。

找不到'对象'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。

另外,将subscribe部分放入组件代码中


0
投票

在你的ngOnInit中,你不需要将返回值赋给this.details,因为当你进行调用时,请求将具有可观察的订阅。您将获得可观察到的成功响应,因此需要成功设置this.details值,如下所示:

ngOnInit() {
    this.api.fetchData().subscribe(response => this.details = response;);
    console.log(this.details);
}
© www.soinside.com 2019 - 2024. All rights reserved.