我有一个模特:
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();
}
这引发了我错误:
错误错误:找不到类型为'object'的其他支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如数组。
已从起源'http://localhost:8080/api/employe'到'http://localhost:4200'对XMLHttpRequest的访问已被CORS策略阻止:在所请求的资源上没有'Access-Control-Allow-Origin'标头。
您正在尝试迭代(循环)对象,根据您的代码示例的外观not一个数组。
这部分是错误的:
pageEmployes:any={};
并且应更改为:
pageEmployes: Employe[] = [];
The“ = {};”初始化一个新的[[object。
The“ = [];”初始化一个新的可迭代的list
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.
响应无效。在春季阅读有关CORS政策的信息https://spring.io/guides/gs/rest-service-cors/关于角度错误,您想遍历对象,因此需要更改
pageEmployes
的类型
pageEmployes:any={};
进入
pageEmployes: Employe[] = [];