使用promise中的数据更新angular2 View / global变量

时间:2015-11-07 19:40:47

标签: javascript angular

我使用fetch从这样的外部API获取数据,并且正确地打印到控制台。但是this.games不会在全局范围内更新,因此视图不会更新。在获取fetch后,如何使用promise中的数据更新全局gams变量:

  import {bootstrap, Component, CORE_DIRECTIVES, Pipe, Inject} from 'angular2/angular2';
  import { Game } from './game/game';
  import { API } from './services/API';
  import {NgZone} from 'angular2/angular2';

@Component({    
selector: 'app',
template: `
Hello
<button (click)="onClickMe()">Click me!</button>
<div *ng-for="#game of games" class = "game">
     //layout
</div>
`,
directives: [CORE_DIRECTIVES, Game],

 })
export class App {
data: any;
api: API;
games: Game[];

constructor(api:API) { 
    this.api = api;
    this.games = [];  
  api.fetchGames().then(function(response) {
        this.data = response;
        console.log(this.data);
        var gamesTemp = [];
        this.teams = this.data.resultSets[1].rowSet;
        for (var i = 0; i < this.teams.length - 1; i += 2) {
            //manipulate            
        }
        this.games = gamesTemp;
        console.log(this.games);
    });

这就是fetchGames方法:

 fetchGames() {

    return fetch('http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=11%2F5%2F2015')
        .then(function(response) {
            return response.json();
        }).catch(function(ex) {
            console.log('parsing failed', ex);
        });
}

1 个答案:

答案 0 :(得分:3)

这似乎是一个范围(this)问题。你回调中的this不是你的班级!最简单的解决方案是使用es6 arrow functions

 import {bootstrap, Component, CORE_DIRECTIVES, Pipe, Inject} from 'angular2/angular2';
  import { Game } from './game/game';
  import { API } from './services/API';
  import {NgZone} from 'angular2/angular2';

@Component({    
selector: 'app',
template: `
Hello
<button (click)="onClickMe()">Click me!</button>
<div *ng-for="#game of games" class = "game">
     //layout
</div>
`,
directives: [CORE_DIRECTIVES, Game],

 })
export class App {
data: any;
api: API;
games: Game[];

constructor(api:API) { 
    this.api = api;
    this.games = [];  
  api.fetchGames().then((response) => { //es6 arrow function was meant to solve this problem!
        this.data = response;
        console.log(this.data);
        var gamesTemp = [];
        this.teams = this.data.resultSets[1].rowSet;
        for (var i = 0; i < this.teams.length - 1; i += 2) {
            //manipulate            
        }
        this.games = gamesTemp;
        console.log(this.games);
    });