Angular 8 NgFor 只支持绑定到 Iterables 比如 Arrays error 和 Acces Control Allow origin

Angular 8 NgFor only supports binding to Iterables such as Arrays error and Acces Control Allow origin

我有一个模型:

export class Employe {    
    constructor(public id?: any,
        public nom?: String,
        public prenom?: String,
        public cin?: String){}    
}

employees.component.ts

ngOnInit(){
    this.loadEmployes();
}    

 pageEmployes:any={};

  loadEmployes():Observable<any>{    
     this.http.get("http://localhost:8080/api/employe").subscribe(
      data=>{
        console.log(data);
        this.pageEmployes = data;

      }, err=>{
        console.log(err);
      }
    );
    return this.pageEmployes;
  }

employees.component.html

 <tr *ngFor="let item of pageEmployes">         
      <td>{{item.nom}}</td>
      <td>{{item.prenom}}</td>    
    </tr>

CollaborateurController.java

@RestController

@RequestMapping("/api/employe")

@CrossOrigin("*")

public class CollaborateurController {

    @Autowired
    private CollaborateurRepository collaborateurRepository;

    @RequestMapping(value="", method=RequestMethod.GET)
    public List<Collaborateur> getEmp() {
        return (List<Collaborateur>) collaborateurRepository.findAll();
    }

这会引发错误:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Access to XMLHttpRequest at 'http://localhost:8080/api/employe' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

您尝试遍历对象而不是数组。将 pageEmployes: any={} 更改为 pageEmployes = []

而这个return this.pageEmployee;是没有必要的,只需将它连同函数的返回值一起删除即可。

http 调用函数更改为:

loadEmployes() {    
     this.http.get("http://localhost:8080/api/employe").subscribe(
      data=>{
        console.log(data);
        this.pageEmployes = data;

      }, err=>{
        console.log(err);
      }
    );
  }

当您使用 console.log(data); 打印您的回复时,您会得到什么数据?

因为

Access to XMLHttpRequest at 'http://localhost:8080/api/employe' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

存在无效响应。 阅读 spring 中的 CORS 政策 https://spring.io/guides/gs/rest-service-cors/

关于 Angular 错误,您想遍历对象,因此需要更改 pageEmployes

的类型
pageEmployes:any={};

进入

pageEmployes: Employe[] = [];

您正在尝试迭代(循环)一个对象,不是一个数组,从您的代码示例来看。

这部分是错误的:

pageEmployes:any={};

并应改为:

pageEmployes: Employe[] = [];

“={};”初始化一个新的 object.

"=[];"初始化一个新的可迭代 list

我遇到了同样的错误。我正在迭代对象而不是数组,所以我用这种方式修复了它

From

 this.faqService.getFaq().subscribe((faqs:any)=>{
      this.faqs = faqs; // here i was trying to iterate over object 
    })

To

>   this.faqService.getFaq().subscribe((faqs:any)=>{
      this.faqs = faqs.data;
      
    })

Console.Log() 并仔细查看您的回复,然后遍历数组,您就可以开始了