Angular在服务器响应后发起请求。

22 浏览
0 Comments

Angular在服务器响应后发起请求。

我试图在服务器回应后进行服务器调用,像这样:

$http.post($scope.serviceSave, {
    'person': $scope.person
}).success(function(data){
    $http.get($scope.serviceList);
});

但是当我尝试这样做时,我得到了`Error: $digest already in progress`的错误,并且请求没有执行。

我尝试使用jQuery来实现,像这样:

People
$scope.setContent = function(service){
    $http.get(service);
}

然后:

$http.post($scope.serviceSave, {
    'person': $scope.person
}).success(function(){
    $("a:contains(People)").click();
});

我可以通过强制点击来进行请求,但是我仍然得到了`Error: $digest already in progress`的错误。

请问,正确的方式是什么?

0
0 Comments

Angular在收到服务器的响应后发出请求的原因是因为使用了回调函数。解决方法是使用deferred对象和promise对象来处理请求。以下是完整的文章:

在Angular中,当我们在回调函数中发出请求时,可能会出现在收到服务器的响应后继续发出请求的情况。以下是一个示例代码:

$http.post("/echo/json/").success(function() {
    console.log("finished 1st");
    $http.get("/echo/json/").success(function() {
        console.log("finished 2nd");
    });
});

在上面的代码中,我们在第一个请求的回调函数中又发出了一个GET请求。尽管这在某些情况下是有效的,但这被认为是一种不良的实践。

为了解决这个问题,我们可以使用deferred对象和promise对象来处理请求。下面是修改后的代码示例:

var deferred = $q.defer();
var promise = deferred.promise;
$http.post("/echo/json/").success(function() {
    console.log("finished 1st");
    deferred.resolve();
});
promise.then(function(){
    $http.get("/echo/json/").success(function() {
        console.log("finished 2nd");
    });
});

在上面的代码中,我们创建了一个deferred对象和一个promise对象。在第一个请求的回调函数中,我们使用deferred.resolve()来触发promise对象的回调函数。然后,在promise对象的回调函数中,我们发出了第二个GET请求。

使用deferred对象和promise对象的好处是可以更好地处理异步请求。通过这种方式,我们可以确保在收到第一个请求的响应后再发送第二个请求。

你可以在以下链接中找到上述代码的工作示例:

[Working fiddle](http://jsfiddle.net/CodeConstructors/KcDQ4/1/)

注意,上述示例代码是针对模拟服务的。在实际应用中,你可能需要根据自己的情况进行适当的修改和调整。

0