2015-11-07 2 views
0

Я использую fetch для получения данных из внешнего API, как это, и он правильно печатает на консоли. Но this.games не обновляется в глобальной области, поэтому представление не обновляется. Как я могу обновить глобальные GAMS переменных с данными внутри обещания раз выборки вернулась:Обновление угловой2 Просмотр/глобальная переменная с данными внутри обещания

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); 
     }); 
} 

ответ

2

Это похоже на сферу (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); 
    }); 
+0

Yup, что исправил его, спасибо большое! – user5534715

Смежные вопросы