Javascript 在属性中存储JSON响应值
我正在进行api调用,并为结果分配了一个属性。然后,我尝试使用此属性修改数据,但出现未定义的错误: 这是我的班级:Javascript 在属性中存储JSON响应值,javascript,angular,Javascript,Angular,我正在进行api调用,并为结果分配了一个属性。然后,我尝试使用此属性修改数据,但出现未定义的错误: 这是我的班级: @Injectable() export class DisplayService { screens: Array<any>; constructor(public http: Http){ } getDisplays() { var path = 'http://localhost:8000/getscreens
@Injectable()
export class DisplayService {
screens: Array<any>;
constructor(public http: Http){
}
getDisplays() {
var path = 'http://localhost:8000/getscreens';
$.ajax({
type: 'GET',
url: path,
success: function(data){
this.screens = data.screens;
}
});
console.log(this.screens);
}
}
@Injectable()
导出类显示服务{
屏幕:阵列;
构造函数(公共http:http){
}
getDisplays(){
var路径http://localhost:8000/getscreens';
$.ajax({
键入:“GET”,
url:path,
成功:功能(数据){
this.screens=data.screens;
}
});
console.log(这个屏幕);
}
}
数据。屏幕
按预期工作;但是,当我console.log
this.screens
时,我得到了未定义的。如何存储响应供以后使用?看起来像是范围问题。。。尝试:
@Injectable()
export class DisplayService {
screens: Array<any>;
constructor(public http: Http){
}
getDisplays() {
var path = 'http://localhost:8000/getscreens';
var that = this;
$.ajax({
type: 'GET',
url: path,
success: function(data){
that.screens = data.screens;
}
});
console.log(this.screens);
}
}
@Injectable()
导出类显示服务{
屏幕:阵列;
构造函数(公共http:http){
}
getDisplays(){
var路径http://localhost:8000/getscreens';
var=这个;
$.ajax({
键入:“GET”,
url:path,
成功:功能(数据){
即.screens=data.screens;
}
});
console.log(这个屏幕);
}
}
我也认为这是问题所在,但遗憾的是,这并不是一个问题。。。ajax很好,异步。。。console.log将在成功触发之前运行。。。完全错过了这一点我可以问一下为什么您要使用jQuery进行通话吗?你为什么不使用Http
(它甚至在你的服务构造函数中)?@EricMartinez我很抱歉,我只是为了让问题更容易理解而更改了它,因为我不确定有多少人熟悉Http