在Angular 2中将Json数据从服务器存储到数组

时间:2017-06-13 19:48:26

标签: arrays json node.js angular typescript

我使用nodejs服务器从SQL数据库中获取数据。

我会将数据存储在tache中,这是一个Tache数组:

getTaches(): Observable<Tache[]> {
  return this.http.get(this.tachesUrl)
    .map(response => {
      this.taches = response.json().data as Tache[];

      console.log(this.taches);
    })
    .catch(this.handleError);

}

当我在控制台上打印时,我会得到结果:

undefined

当我打印response.json()时,我得到了我的值:

Object {taches: Array(8)}

所以我删除.data并再试一次,然后我在模板文件的第1行得到另一个错误:

 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

这是我的html文件:

         <md-toolbar color="primary">
      <span>Taches non traitées</span>
    </md-toolbar>
        <md-card>


            <md-list   >
                      <ng-container *ngFor="let tache of this.tacheService.taches   "  >

                <md-list-item *ngIf="tache.stat == 0" (click)="onSelect(tache)" [class.selectionnee]="tache === tacheSelectionnee">{{tache.stat}}+{{tache.id}} + {{tache.name}}

                    <div *ngIf="tache === tacheSelectionnee">

                        <button md-icon-button  [mdMenuTriggerFor]="menu">
                            <md-icon>more_vert</md-icon>
                        </button>
                        <md-menu #menu="mdMenu">
                            <button md-menu-item (click)="openDialog(tache)">
                                <md-icon>edit</md-icon>
                                <span>Modifier</span>
                            </button>
                            <button md-menu-item (click)="delete(tache)">
                                <md-icon>delete</md-icon>
                                <span>Supprimer</span>
                            </button>
                            <button md-menu-item (click)="save(tache)">
                                <md-icon>cached</md-icon>
                                <span>Traiter</span>
                            </button>
                        </md-menu>


                    </div>

                </md-list-item>

                </ng-container>

            </md-list>
        </md-card>

我会正确地将数据存储在taches数组中,以便我可以将它们显示为todo list。

1 个答案:

答案 0 :(得分:1)

试试这个:

getTaches(): Observable<Tache[]> { 
    return this.http.get(this.tachesUrl)
      .map(response => {
         this.taches = response.json().taches as Tache[];

  console.log(this.taches);
})
  .catch(this.handleError);
}

从api收到的对象包含taches数组