角JS $ HTTP工厂模式工厂、模式、JS、HTTP

由网友(哥的微笑′百度里搜不到)分享简介:我有一个工厂命名为userService。I've a factory named as 'userService'..factory('userService', function($http) {var users = [];return {getUsers: function(){return $http.g...

我有一个工厂命名为userService。

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

在第一页,在点击链接我要打电话getUsers函数,它将返回用户阵列。

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:我使用的getter和setter存储在第一页的响应和访问相同的第二页。这是每个人的方式在做什么?

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?

推荐答案

下面是我按照我自己的项目的模式。你可以看到下面

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

服务呼叫后设置常用数据工厂的响应数据,因此,这将是整个应用程序

访问

在上面的code我用普通的数据工厂存储响应。

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.

阅读全文

相关推荐

最新文章