gpt4 book ai didi

typescript - 构造函数中的 Angular2 http.get 看不到 'this'

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:50 25 4
gpt4 key购买 nike

我正在尝试从服务器获取数据,而类的构造函数看不到类的 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()

中返回它

最佳答案

你应该为你的回调使用箭头函数,以便能够使用词法 this:

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

有关箭头函数的词法 this 的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions .

关于typescript - 构造函数中的 Angular2 http.get 看不到 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230323/

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