0
使用fetch從外部API中獲取數據,並且它正在正確地打印到控制檯。但是,this.games不會在全局範圍內更新,所以視圖不會更新。我怎樣才能從承諾中更新的數據變量全球GAMS一旦獲取返回:更新angular2視圖/承諾數據中的數據的全局變量
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);
});
}
是的,它固定它非常感謝! – user5534715