角JS $ HTTP工厂模式 [英] Angular js $http factory patterns

查看:195
本文介绍了角JS $ HTTP工厂模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂命名为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.

这篇关于角JS $ HTTP工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆