Angular9:获取找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到数组等Iterables

时间:2020-04-19 12:11:58

标签: angular typescript

我已经创建了一个简单的应用程序来使用HttpClientModule调用后端服务,但是数据没有显示到日志中,我执行了以下步骤,并且我使用的是angular-9

请检查代码。

预先感谢。

  1. app.module文件
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule} from '@angular/common/http';
import {RestAPIServices} from './services/rest-api.service';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [RestAPIServices],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. model.ts
export class Employee{
    id:number;
    name:string;
    gender:string;
    email? :string; // ? means optional property
    mobile:string;
    department:string;
    isActive:boolean;
    photo? :string;
}
  1. service.ts
import {Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {HttpClient} from '@angular/common/http';
import { Employee } from '../models/employee.model';

@Injectable()
export class RestAPIServices{

    constructor(private httpClient:HttpClient){}

   getEmployee():Observable<Employee[]>{
    //this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees").subscribe(res=>  console.log(res));
    return this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees");
   }

}
  1. app.component.ts
import { Component } from '@angular/core';
import {RestAPIServices} from './services/rest-api.service';
import {Employee} from './models/employee.model';

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

  listEmployee : Employee[];
  title = 'simple-rest-app';

  constructor(private _employeeService:RestAPIServices){}
  ngOnInit(){

    this._employeeService.getEmployee().subscribe(
      data=>{
        console.log(data)
        this.listEmployee = data;
      }
    )

    console.log(this.listEmployee);
  }

}

servire经过邮递员的测试,工作正常

{"response":[{"id":"1","name":"Anand","gender":"Male","email":"a@gmail.com","mobile":"111111111","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"2","name":"Kiran","gender":"Female","email":"k@gmail.com","mobile":"2222222222","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"3","name":"Ravi","gender":"Male","email":"r@gmail.com","mobile":"3333333333","department":"2","isActive":"1","photo":"assets\/images\/emp2.jpg"},{"id":"4","name":"Kumar","gender":"Male","email":"k@gmail.com","mobile":"4444444444","department":"3","isActive":"1","photo":"assets\/images\/emp4.jpg"}]}

1 个答案:

答案 0 :(得分:1)

看起来像问题在于服务器响应是对象,而不是数组。

// try to replace
this.httpClient.get<Employee[]>(...);

// by
this.httpClient.get<{ response: Employee[] }>(...).pipe(
  map(response => response.response)
);