2016-02-05 61 views
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()

回答

2

你應該使用箭頭功能,爲您的回調返回它能夠使用的詞彙this

.subscribe((data) => { 
    this.games = []; 
    var response = data.json(); 
    (...) 
}); 

請參閱有關的箭頭功能詞法此此鏈接,更多的提示:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

+0

確實'var games = [];''在本地創建?我需要從課堂上得到變量。 –

+0

您可以直接使用'this.games = [];'。 'this'對應於組件實例。我更新了我的答案。 –

相關問題