After Angular.js $http request, call complete function regardless of success or failure of promise

前端 未结 3 1306
礼貌的吻别
礼貌的吻别 2021-02-13 18:46

How can I ensure that the complete() function will run regardless of the outcome of the $http call using the promise API provided with Angular.js?

$         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-13 19:39

    If you don't care if the request is successful or not, then you can pass the same callback to success and error...

       var cb = function(response){
          // do something
       };
    
    
       $http.post(submitUrl, $scope.data).success(cb).error(cb);
    
       // OR
    
       $http.post(submitUrl, $scope.data).then(cb, cb);
    

    But be aware that success and error callbacks have a different signature than the then callbacks.

    • http://docs.angularjs.org/api/ng.$http
    • http://docs.angularjs.org/api/ng.$q

    Also, promises are recognized by the templating engine in angular, which means that in templates you can treat promises attached to a scope as if they were the resulting values.

    This means that you can do this:

    Controller:

    $scope.article = $http.get('/articles/' + articleId);
    

    Template:

    {{article.title}}

    {{article.content}}

    And the view will update when the $http.get promise has been resolved.

提交回复
热议问题