Angular js $http factory patterns

岁酱吖の 提交于 2019-12-04 20:15:47

Here is the pattern i have followed in my own project. You can see the code below

.factory('userService', function($http) {
return {
        serviceCall : function(urls, successCallBack) {

                $http({
                    method : 'post',
                    url : url,
                    timeout : timeout
                }).success(function(data, status, headers, config) {
                        commonDataFactory.setResponse(data);
                }).error(function(data, status, headers, config) {
                        commonDataFactory.setResponse({"data":"undefined"});
                        alert("error");
                });
            }
        },
    };

After service call set the response data in common data factory so that it will be accessible throughout the app

In the above code I've used common data factory to store the response.

1). getUsers. For consistence sake I would still use the same service method on the second page but I would also add data caching logic:

.factory('userService', function($q, $http) {

    var users;

    return {
        getUsers: function() {
            return users ? $q.when(users) : $http.get("https://www.yoursite.com/users").then(function(response) {
                users = response;
                return users;
            });
        },
        getUser: function(index){
            return users[i];
        }
    };
});

Now on the second page usage is the same as it was on the first:

userService.getUsers().then(function(users) {
    $scope.users = users;
});

but this promise will resolve immediately because users are already loaded and available.

2). getUser. Also it makes sense to turn getUser method into asynchronous as well:

getUser: function(index){
    return this.getUsers().then(function(users) {
        return users[i];
    });
}

and use it this way in controller:

userService.getUser(123).then(function(user) {
    console.log(user);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!