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

查看:25
本文介绍了Angular 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 函数,它将返回 'users' 数组.

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

我想在第二页中使用 'users' 数组.我该怎么做?

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

服务调用后在公共数据工厂中设置响应数据,以便在整个应用程序中都可以访问

在上面的代码中,我使用了通用数据工厂来存储响应.

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.

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

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