在angular 7中列出json数据时,出现错误“错误:尝试区分'[object Object]'时出错。仅允许数组和可迭代对象”

时间:2019-02-11 10:45:22

标签: angular7

当在angular 7中列出json数据时,出现错误“错误:尝试与'[object Object]'进行比较时出错。仅允许数组和可迭代对象”

这是我的component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[ApiService]
})
 export class AppComponent {
 Form:any[]=[]

  constructor(private api:ApiService){}

ngOnInit(){
  this.getForms();

}

getForms=()=>{
 this.api.getAllForms().subscribe(
   data=>{
    this.Form=data;
    console.log(data);
  },
  error=>{
    console.log(error);
  }
  );
}
}

这是我的component.html,我只想列出全名。

 <ul>
  <li *ngFor="let form of Form">
  <h2>{{form.fullname}}</h2>
  </li>
  </ul>

这是我的服务。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';


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

baseurl= "http://127.0.0.1:8000";
httpHeaders=new HttpHeaders({'Content-Type':'application/json'});

constructor(private http:HttpClient) { }

  getAllForms(): Observable<any> {
    return this.http.get(this.baseurl+'/forms/',
    {headers: this.httpHeaders});
  }
}

This is what I get in console

2 个答案:

答案 0 :(得分:0)

您必须以getAllForms(): Observable<any[]>的数组形式而不是getAllForms(): Observable<any>的形式传递

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';


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

baseurl= "http://127.0.0.1:8000";
httpHeaders=new HttpHeaders({'Content-Type':'application/json'});

constructor(private http:HttpClient) { }

  getAllForms(): Observable<any[]> {
    return this.http.get(this.baseurl+'/forms/',
    {headers: this.httpHeaders});
  }
}

答案 1 :(得分:0)

@Sudeep Sharma,我没有在控制台数据中找到任何名称为fullname的变量,并将getAllForms()的返回类型更改为Observable<any[]>,这将返回表单列表。

  

Service.ts

  getAllForms(): Observable<any[]> {
       return this.http.get(this.baseurl+'/forms/',{headers: this.httpHeaders});
  }