处理 Angular 中的非幂等$http请求

Dealing with non-idempotent $http requests in Angular

本文关键字:http 请求 Angular 处理      更新时间:2023-09-26

我在概念化如何在整个应用程序中对来自非幂等请求的数据进行建模/访问时遇到了麻烦。

例如,我们假设我有一个 API,它返回一个随机作者供用户查看。 我需要在应用的不同位置显示有关此作者的信息,然后偶尔需要重新调用 getNext 方法来获取下一个随机作者,并更新应用中的所有绑定。

我有以下工厂:

.factory('author', function($http) {
    return {
        data: {},
        getNext: function() {
            return $http.get('/path/to/endpoint').then(function(res) {
                angular.copy(res.data, this.data)
                return res;
            }.bind(this));  
    };    
});

然后,在我的控制器中,我只需适当地绑定数据:

.controller('MainCtrl', function($scope, author) {
    $scope.author = author.data;
    author.getNext();
});

并呈现了我视图中的数据:

<h2>{{author.name}}</h2>
<div ng-repeat="book in author.books">
    {{book.title}} - {{book.year}}
</div>

这有效,但是将新对象复制到旧对象中以获取要触发的更新感觉有点笨拙。

更重要的是,除了我最初调用它的控制器之外,我无法访问任何其他控制器中getNext生成的承诺。 我想做的是data成为最后的getNext承诺。 这意味着如果我调用一个新的getNextdata成为新的承诺,我所有的.then都会在加载时重新执行。

也许data需要成为我解决的$q.defer()

我不会让"作者"服务充当作者实体,我只会将其用作 DAO。

.factory('Author', function($http) {
    function AuthorService(){
        this.getNext = function(){
            return $http.get('/path/to/endpoint').then(function(res) {
                return res.data; 
            })
        } 
    }; 
    return new AuthorService()   
});
.controller('MainCtrl', function($scope, Author) {
      Author.getNext().then(function(author){
         $scope.author = author
      });
});