[英]“this” variable not working when assigning JSONP array to AngularJS controller
I have a REST service that I call in my angular controller via JSONP. 我有一个REST服务,可以通过JSONP在我的角度控制器中调用。 I want to save the returned array to a variable.
我想将返回的数组保存到变量。
Here is what I am doing: 这是我在做什么:
this.testTheRest = function()
{
$http.jsonp('myRESTService', {
params: {
callback: 'JSON_CALLBACK',
format: 'json'
}
})
.success(function (data) {
this.testlist = data.NoParamsResult;
console.log(this.testlist);
})
.error(function (data) {
alert(data);
});
console.log(this.testlist);
}
I have defined testlist as a variable in the controller beforehand: 我已经预先将testlist定义为控制器中的变量:
this.testlist = [];
Note the two console output calls. 注意两个控制台输出调用。 The problem is, that the first one shows the correct array:
问题是,第一个显示正确的数组:
Array [ Object, Object ]
But the second one shows an empty array (probably the one from initialization): 但是第二个显示一个空数组(可能是初始化中的一个):
Array [ ]
What do I have to do to keep the returned objects in the array? 我该怎么做才能将返回的对象保留在数组中?
Thanks in advance, 提前致谢,
Frank 坦率
This is a scoping issue. 这是一个范围界定问题。 Try assigning your outer
this
to another variable (eg that
), then using that variable instead of this
. 尝试将您的外部
this
分配给另一个变量(例如that
),然后使用该变量代替this
。
var that = this
that.testTheRest = function() {
$http.jsonp('myRESTService', {
params: {
callback: 'JSON_CALLBACK',
format: 'json'
}
})
.success(function (data) {
that.testlist = data.NoParamsResult;
console.log(that.testlist);
})
.error(function (data) {
alert(data);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.