gpt4 book ai didi

angular - 在 Angular2 中获取

转载 作者:太空狗 更新时间:2023-10-29 19:31:27 26 4
gpt4 key购买 nike

在这里使用 fetch 的正确方法是什么?现在我的应用程序正在后台加载 JSON(我可以在 Chrome 的开发人员工具中看到它)但是 this.games 在执行后未定义,我不知道为什么。我假设我返回的数据有误。

现在我的 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();
})
}
}

最佳答案

我想这与 this one 是同一个问题.问题在范围内('this') - promise 回调中的'this'不是类。最简单的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);
});

关于angular - 在 Angular2 中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com