Angular js $http factory patterns

北城余情 提交于 2019-12-06 12:55:53

问题


I've a factory named as 'userService'.

.factory('userService', function($http) {
    var users = [];

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

In the first page, On button click I want to call getUsers function and it will return the 'users' array.

I want to use 'users' array in the second page. How can I do it?

P.s: I'm using getters and setters to store the response in first page and access the same in second page. Is this the way everyone doing?


回答1:


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.




回答2:


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);
});


来源:https://stackoverflow.com/questions/26657228/angular-js-http-factory-patterns

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