2
我想從服務器獲取數據,並且類的構造函數不能看到類this
以將傳入數據保存到變量this
。在構造函數中的Angular2 http.get不能看到'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
I類聲明games:GameModel[]
。構造函數不能看到games:GameModel[]
。收到數據後,我想在getGames()
確實'var games = [];''在本地創建?我需要從課堂上得到變量。 –
您可以直接使用'this.games = [];'。 'this'對應於組件實例。我更新了我的答案。 –