Javascript angularjs承诺无法正确解决问题
我的控制器已注入所有必需的依赖项Javascript angularjs承诺无法正确解决问题,javascript,angularjs,angularjs-scope,promise,Javascript,Angularjs,Angularjs Scope,Promise,我的控制器已注入所有必需的依赖项 $scope.connect = function(url) { var defer = $q.defer(); var promise = $http.get(url).then(function (response) { $timeout(function(){ defer.resolve(response); },10000); defer.reso
$scope.connect = function(url) {
var defer = $q.defer();
var promise = $http.get(url).then(function (response) {
$timeout(function(){
defer.resolve(response);
},10000);
defer.resolve(response);
$scope.$apply(); //$rootScope.$apply();
});
return defer.promise;
};
$scope.mymethod = function(){
$scope.globalMydata[];
console.log("before the http get");
$scope.connect("MY_URL").then(function(data) {
console.log("called!", data);
console.log("INSIDE the http get");
$scope.mydata = data;
//$scope.globalMydata.push(data);
});
console.log("after the http get ");
//do some processing of the returned data here
var dataHolder = $scope.mydata;
return calculatedValue;//value from procesing
}
在执行代码时,“在http get内部”作为最后一个调试日志被调用。我从get调用中获取结果,但由于它稍后返回,我无法对其进行任何处理。这就是为什么我们承诺正确的原因?我需要承诺的数据在控制器内进行一些处理
我的承诺执行中有什么问题吗 我不确定是否理解你的问题,但看起来你已经建立了一个承诺中间接受者,但从你的问题来看,你似乎只想要常规的承诺行为。那我就试试看 我不是一个角度专家,但我确实经常使用$http承诺,下面是我如何做到这一点的 我将$http调用注册为服务,如下所示:
app.service('ajax',function(host,$http){
this.post = function(api,data,cb){
$http.post(host + api,data).success(cb)
};
this.get = function(api,cb){
$http.get(host + api).success(cb)
}
});
ajax.post('users', UserToken, function(data){
console.log('Users points: ' + data.points)
})
主机是预定义的。我将此服务注入每个需要调用http请求的控制器,并按如下方式操作它们:
app.service('ajax',function(host,$http){
this.post = function(api,data,cb){
$http.post(host + api,data).success(cb)
};
this.get = function(api,cb){
$http.get(host + api).success(cb)
}
});
ajax.post('users', UserToken, function(data){
console.log('Users points: ' + data.points)
})
据我所知,$http内置了承诺,因此不需要q和延迟,所有这些都是在后台完成的ajax.post
调用该服务,该服务将数据
发送到主机+“用户”
,服务器端通过其令牌查找用户,并使用点的名称返回一些数据,其中包含用户点的值。客户端:从服务器成功回复后,它进入cb
功能,然后控制台记录用户点
因此,我可以对cb函数中的承诺做任何需要的修改,因为在服务器成功回复之前不会调用它
success
和error
方法还有一些可选参数,请检查它们。应该是$scope.mydata=data.data代码>。您不需要执行$scope.$apply()
另外,然后在收到响应后执行。因此,您可以在http get
部分之后将移动到then
函数中。理想情况下,我希望获得响应,然后在控制器中处理它,而不是移动then函数中的逻辑。顺便说一句,承诺的要点是在理想情况下促进asnyc调用,它必须等待http调用中的所有数据加载完毕,然后继续页面的其余部分?我说得对吗?