我有一个视图,调用下面的函数对我们的API进行AJAX调用 - 由于某些原因,当我使用Firefox DOM检查工具在AngularScope中查看时,它总是返回'undefined'。
如果我检查网络选项卡,我可以看到此URL已被调用,并且可以看到我期望的JSON,然后我想返回data.words JSON数据,但这总是返回undefined?如果我删除了AJAX调用,并且在最后一次返回中使用'static'和'words'按预期工作,那么我很清楚在AJAX成功调用中返回的内容似乎不正确......任何想法??
//在AngularJS服务文件中
this.getAccSignoffWords = function() {
var url = ApiService.getDomain() + 'account/signoff';
$http({
method : 'GET',
url : url
}).success(function(data) {
if (data.success) {
return data.words; // I want to return this JSON to the scope
}
}).error(function(data) {
throw "Failed to get sign-off words";
})['finally'](function(data) {
});
// return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words
}
答案 0 :(得分:1)
那是因为你的ajax没有返回任何内容..如果你想将它分配给你应该做的范围:
var self = this;
var url = ApiService.getDomain() + 'account/signoff';
$http({
method : 'GET',
url : url
}).success(function(data) {
if (data.success) {
self.getAccSignoffWords = data.words; // I want to return this JSON to the scope
}
}).error(function(data) {
throw "Failed to get sign-off words";
})['finally'](function(data) {
});
答案 1 :(得分:1)
事情是,当您发送http请求时,需要一些时间来处理并将数据发送回您的javascript代码。但由于javascript是异步的,因此它不会等到响应返回。所以要么你可以返回像 Umakanta Behera 建议的整个http请求,要么你可以使用回调函数来等待响应单位回来。
communicate
像这样调用这个函数
this.getAccSignoffWords = function(callback) {
var url = ApiService.getDomain() + 'account/signoff';
$http({
method : 'GET',
url : url
}).success(function(data) {
if (data.success) {
callback() data.words
}
}).error(function(data) {
throw "Failed to get sign-off words";
})['finally'](function(data) {
});
}
答案 2 :(得分:0)
我认为你没有重新调整$ http结果。请你试试下面的代码。
this.getAccSignoffWords = function() {
var url = ApiService.getDomain() + 'account/signoff';
return $http({
method : 'GET',
url : url
}).success(function(data) {
if (data.success) {
return data.words; // I want to return this JSON to the scope
}
}).error(function(data) {
throw "Failed to get sign-off words";
})['finally'](function(data) {
});
// return [ 'static', 'words' ]; // this line is commented out and only used for testing and is an example of the type of data expected from data.words
}