在这里使用fetch的正确方法是什么?现在我的应用程序正在后台加载JSON(我可以在Chrome的开发者工具中看到它)但是这个游戏在执行后未定义,我无法弄清楚原因。我假设我错误地返回了数据。
现在我在app.ts
中有这个import {bootstrap, Component, View, CORE_DIRECTIVES, Pipe} from 'angular2/angular2';
import { Game } from './game/game';
import { API } from './services/API';
@Component({
selector: 'app',
template: `
{{games}}
`,
directives: [CORE_DIRECTIVES, Game]
})
export class App {
games: any;
constructor(api: API) {
api.fetchGames().then(function(json){
this.games = json;
});
};
}
bootstrap(App, [API]);
和我的API.ts:
declare var Zone, fetch, Request;
export class API {
data: any;
fetchGames() {
return fetch('http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=11%2F5%2F2015',{mode:'no-cors'})
.then(function(response){
return response.json();
})
}
}
答案 0 :(得分:1)
我想这与this one的问题相同。问题在于范围('this') - 'this'内部的promise回调不是类。最简单的es6解决方案是更改为es6 arrow function:
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 will preserve class' 'this'
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);
});