0

我的控制器注入了所有必需的依赖项。

 $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

}

当代码被执行时,“INSIDE the http get”作为最后的调试日志被调用。我从 get 调用中得到结果,但由于它稍后返回,我无法对其进行任何处理。这就是我们承诺的确切原因吗?我需要承诺的数据在控制器内部进行一些处理。

我的承诺实施中有任何问题吗?

4

1 回答 1

1

我不确定我是否得到你的问题,但看起来你已经建立了一个承诺 interseptor,但从你的问题来看,你似乎只想要常规的承诺行为。那我试试看。。

我不是角度专家,但我确实经常使用 $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)
  }
});

host 是一个预定义的module.value。我将此服务注入到每个需要调用 http 请求并像这样操作它们的控制器中:

ajax.post('users', UserToken, function(data){
  console.log('Users points: ' + data.points)
})

据我了解,$http 内置了 Promise,因此不需要 q 和 defere,这一切都在后台完成。ajax.post调用该服务,该服务发送datahost + 'users',服务器端通过他的令牌查找用户并返回一些数据,其中一个键的名称为points用户点的值。客户端:在服务器成功回复后,它会继续执行cb控制台记录用户点的功能。

因此,我可以对该 cb 函数中的 promise 进行任何我需要的修改,因为在服务器成功回复之前不会调用它。

successand方法还有error一些可选参数,请在此处查看

于 2013-09-05T07:57:53.337 回答