【问题标题】:Store Json data from server to array in Angular 2在Angular 2中将Json数据从服务器存储到数组
【发布时间】:2017-11-15 18:01:22
【问题描述】:

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

我会将数据存储在 taches 中,这是一个 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 数组中,以便将它们显示为待办事项列表。

【问题讨论】:

    标签: arrays json node.js angular typescript


    【解决方案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 数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2017-10-19
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多