将promise数据推送到对象数组中

时间:2017-11-07 22:00:37

标签: angular typescript

如何在this.players内推送承诺的数据?在我尝试推送时,此代码this.players未定义

import { Component } from '@angular/core';
import { MyDataServiceService } from './my-data-service.service';
import { Player } from './player';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  players:Player[];

  constructor ( private service:MyDataServiceService){}

  ngOnInit(){
    this.service.getData().subscribe((data) => {
      var json_data = data.json().resultSets[0]['rowSet'];
      for (let player of json_data) {
        this.players.push(new Player(player[0],player[1],player[3],player[4]));
      }
    });
  }
}

2 个答案:

答案 0 :(得分:0)

如果玩家是模特,你可以做这样的事情。

players: Array<Player> = [];

答案 1 :(得分:0)

使用点差运算符

this.players = [ ...this.players, ...player];