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

时间:2018-06-08 15:55:27

标签: arrays angular object service components

以下是代码:

component.ts

在路由中选择匹配geting id,然后从URL

中获取此ID
export class MatchComponent implements OnInit {
_postArrayMatch: match[];

 constructor(public router:Router, private matchService: MatchService, 
 private route: ActivatedRoute) {}

 ngOnInit(){
 this.getMatchId();
 }

 getMatchId() :void {
 this.route.params.forEach((params: Params)=> {
  let id = +params['id'];



  this.matchService.getMatch(id).subscribe(
    resultArray => this._postArrayMatch = resultArray,
    error => console.log("Error ::" + error))
  })
 }

component.html

通过执行ngFor循环

进行基本插值
 <div *ngFor="let post of _postArrayMatch">
 <p>{{post.team1.name}}</p>
 </div>

service.ts

传递动态ID

 getMatch(id:number): Observable<match[]>{
    return this.http.get<match[]>(`http://localhost:3000/match/${id}`)
    }

接口

   export interface match{
     team1:{
      name:string,
      id:number
     }
     team2:{
      name:string,
      id:number
     }
   }

2 个答案:

答案 0 :(得分:0)

这似乎是我找到如何从对象获取数据的最简单方法。

objectKeys = Object.keys;

component.ts

$(".first-input").val()

答案 1 :(得分:0)

尝试在响应中创建对象的类似内容

<强> component.ts

export class MatchComponent implements OnInit {
_postArrayMatch: match[];
newArr: Array<Object> = [];

 constructor(public router:Router, private matchService: MatchService, 
 private route: ActivatedRoute) {}

 ngOnInit(){
   this.getMatchId();
 }

 getMatchId() :void {
  this.route.params.forEach((params: Params)=> {
  let id = +params['id'];



  this.matchService.getMatch(id).subscribe(
    resultArray => {
      this._postArrayMatch = resultArray;
      const keys = Object.keys(this._postArrayMatch) // new stuff starts here
      for(let i = 0; i < keys.length; i++) { 
        newArr.push(this._postArrayMatch[keys[i]]);
        newArr[i]['team'] = keys[i];
      }
    },
    error => console.log("Error ::" + error))
  })
 }

然后您可以访问html中的所有子对象

<强> Component.html

 <div *ngFor="let post of newArr">
  <p> {{post.team}}: {{post.name}}</p>
 </div>

目前,您拥有的是第1组的强硬编码,如果您想这样做,那么您就不应该使用*ngFor