【发布时间】:2018-10-01 07:44:49
【问题描述】:
我正在使用 AngularJS http.post 发布,将 response.data 放入 successCallback 函数的范围内。 console.log 写入范围数据,但我无法在另一个函数中访问范围数据。
Init 为请求调用函数。
$scope.init = function(group_year_id,year)
{
accessScopeFunction();
foo();
};
这是被调用的函数
function accessScopeFunction() {
$http({
method: 'POST',
url: 'http://localhost/sjb/public/admin/groups/assing/angular/get/databasename'
}).then(function successCallback(response) {
$scope.getDatabaseName = response.data.event_db;
console.log($scope.getDatabaseName);
}, function errorCallback(response) {
return 'Fault';
});
};
我想将 $scope.getDatabaseName 传递给另一个函数
function foo() {
$http({
method: 'POST',
url: 'http://localhost/sjb/',
data: {'databasename':$scope.getDatabaseName}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
};
我阅读了很多关于 Promise、AngularJS 文档等的信息,但我找不到适合我的合适解决方案。
【问题讨论】:
-
何时以及如何调用
foo()?您如何保证在accessScopeFunction()中的请求完成后调用它? -
foo() 在 init 中的 accessScopeFunction() 之后调用。刚刚更新了我的问题。
-
那很可能是你的问题。您正在发出 asyncronous (ajax 中的“a”)请求。您的代码触发请求然后继续运行,它不会等待响应。因此,您在第一个请求中的
then回调可能要等到 您的foo()函数被调用后才会发生。 -
这解释了很多,但是解决这个问题的正确解决方案是什么,所以我可以在 foo() 函数中使用 $scope.getDatabaseName 和一个值(现在它是未定义的),因为我可以'找不到它
-
在
accessScopeFunction()的回调中调用foo()