我正在尝试从服务器获取数据,并且类的构造函数无法查看类的this
以将传入数据保存到this
的变量。
import {Injectable} from '/angular2/core';
import {GameModel} from 'app/model/games/games';
import {Component} from "angular2/core";
import {HTTP_PROVIDERS, Http} from 'angular2/http';
@Component({
providers: [HTTP_PROVIDERS, Http]
})
export class DataProvider {
games:GameModel[];
constructor(private http:Http) {
console.log('this.games constructor', this.games); //undefined
http.get('app/service/php/games.php')
//.map(res => res.json())
.subscribe(function (data) {
var games = [];
var response = data.json();
for (var i = 0; i < response.length; i++) {
var game = new GameModel(
response[i].id,
response[i].gameName,
response[i].fullName,
response[i].altname,
response[i].description,
response[i].minPlayers,
response[i].maxplayers,
'',
response[i].bgglink);
games.push(game);
}
this.games = games;
console.log('this.games', this.games); //undefined
});
}
getGames() {
return Promise.resolve(this.games);
}
}
在课程DataProvider
中,我声明games:GameModel[]
。构造函数无法看到games:GameModel[]
。收到数据后,我想在getGames()
答案 0 :(得分:2)
您应该使用回调功能的箭头功能来使用词法this
:
.subscribe((data) => {
this.games = [];
var response = data.json();
(...)
});
有关箭头函数词汇的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。