typescript - Angular2 http.get in constructor can't see 'this' -


i trying data server, , constructor of class can't see this of class save incoming data variable this.

import  {injectable} '/angular2/core'; import {gamemodel} 'app/model/games/games'; import {component} "angular2/core"; import {http_providers, http} '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();                  (var = 0; < 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);     } } 

in class dataprovider declare games:gamemodel[]. constructor can't see games:gamemodel[]. after receive data want return in getgames()

you should use arrow functions callbacks able use lexical this:

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

see link more hints lexical of arrow functions: https://developer.mozilla.org/en-us/docs/web/javascript/reference/functions/arrow_functions.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -