angularJS开发promise对象使用方法

创建一个服务对象:

.factory("UserSerice",function($q,$http,ajax){
    var _url = '/api/v1/user/';

    return {
        get:function(id,param){
            var defer = $q.defer();
            $http.get(ajax.parseParam(_url + id,param))
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        save:function(param){
            var defer = $q.defer();
            $http.post(_url,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        put:function(id,param){
            var defer = $q.defer();
            $http.put(_url + id,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        }

    }
})

 

服务包含增改查,3种方法,下面是使用方法:

.controller("controllerMain", function ($scope,UserSerice) {
    var user_promise;
    $scope.get = function () {
        c($scope.user_id)
        user_promise = UserSerice.get($scope.user_id,{});
        user_promise.then(function(data){
            c("user_promise:succ")
            c(data);

        },function(data){
            c("user_promise:err")
            c(data);

        });


    }

    $scope.save = function () {
        user_promise = UserSerice.save({user_name:$scope.user_name,user_pwd:$scope.user_pwd,email:$scope.email});
        user_promise.then(function(data){
            c("save:user_promise:succ")
            c(data);
            if(data.response_code == 1){
                $scope.user_id = data.user_id;
            }

        },function(data){
            c("save:user_promise:err")
            c(data);

        });

    }

    $scope.put = function () {

        user_promise = UserSerice.put($scope.user_id,{user_name:$scope.user_name,user_pwd:$scope.user_pwd,email:$scope.email});
        user_promise.then(function(data){
            c("put:user_promise:succ")
            c(data);

        },function(data){
            c("put:user_promise:err")
            c(data);

        });

    }

})

 

angularJS创建拦截注入$httpProvider、interceptor 、auth

angularJS创建拦截注入,为每个$http请求添加auth权限请求:

var app = angular.module("myApp", ["ngRoute", "ngResource"])
    .constant('ACCESS_LEVELS',{
        PUB:1,
        USER:2
    })
    .config(["$routeProvider", "$httpProvider","ACCESS_LEVELS", function ($routeProvider, $httpProvider,ACCESS_LEVELS) {

        //设置http头
        $httpProvider.defaults.headers.common["X-Response-Code-By"] = "Angular1.5.8";

        var interceptor = function ($q, $rootScope, auth) {
            return {
                'response': function (res) {
                    //登录成功,设置authkey
                    if (res.config.url.indexOf('/api/v1/login')!=-1) {
                        auth.set(res.data.auth);
                    }
                    return res;
                },
                'responseError': function (rejection) {
                    switch (rejection.status) {
                        case 401:
                            if (res.config.url.indexOf('/api/v1/login')!=-1) {
                                // 如果当前不是在登录页面
                                $rootScope.$broadcast('auth:loginRequired');
                            }
                            break;
                        case 403:
                            $rootScope.$broadcast('auth:forbidden');
                            break;
                        case 404:
                            $rootScope.$broadcast('page:notFound');
                            break;
                        case 500:
                            $rootScope.$broadcast('server:error');
                            break;

                    }
                    return $q.reject(rejection);
                },
                'request': function (config) {

                    //为每条服务器请求加入auth权限
                    if(config.url.indexOf("api/v1/") > -1){
                        if(config.url.indexOf("?") != -1){
                            config.url += "&auth="+auth.get();
                        }else{
                            config.url += "?auth="+auth.get();
                        }

                    }
                    return config;
                },
                'requestError': function (rejection) {
                    if (canRecover(rejection)) {
                        return responseOrNewPromise
                    }
                    return $q.reject(rejection);
                },
            };
        };


        $httpProvider.interceptors.push(interceptor);

        //路由
        $routeProvider
            .when("/", {
                templateUrl: "view/main.html",
                controller: "controllerMain",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/list/:id", {
                templateUrl: "view/list.html",
                controller: "controllerList",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/about", {
                templateUrl: "view/about.html",
                controller: "controllerAbout",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/contact", {
                templateUrl: "view/contact.html",
                controller: "controllerContact",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/login", {
                templateUrl: "view/login.html",
                controller: "controllerLogin",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/register", {
                templateUrl: "view/register.html",
                controller: "controllerRegister",
                access_level:ACCESS_LEVELS.PUB
            })
            .when("/uc_enter", {
                templateUrl: "view/uc_enter.html",
                controller: "controllerUcenter",
                access_level:ACCESS_LEVELS.USER
            })
            .otherwise({redirectTo: '/'})
    }])
    .run(function ($rootScope, $location,auth,cookieUtils,ajax) {
        auth.set(cookieUtils.get("auth"));

        $rootScope.title = "本地网站";
        $rootScope.keywords = "网站的关键词";
        $rootScope.description = "网站的描述";

        $rootScope.isActive = function (score) {
            return score == $location.path();
        };

        //判断是否登录
        $rootScope.isLogin = function(){
            return !auth.get();
        }

        //路由开始
        $rootScope.$on('$routeChangeStart', function (evt, next, current) {

            //boot菜单选择器
            if($(".navbar-toggle").attr('aria-expanded') == "true"){
                $(".navbar-toggle").click();
            }
            if(next.$$route.access_level == 2 && auth.get().length == 0){
                toast("请先登录!");
                $location.path("/login");
            }
        });

        //路由成功
        $rootScope.$on('$routeChangeSuccess', function (evt, next, previous) {

        });

        //路由错误
        $rootScope.$on('$routeChangeError', function (current, previous, rejection) {
            c('$routeChangeError')
            c(current)
            c(previous)
            c(rejection)
        });

        //登出
        $rootScope.loginOut = function(){
            ajax.get("/api/v1/loginOut",{})
                .success(function(data){
                    if(data.response_code == 1){
                        auth.del();
                        if(toast(data.response_err)){
                            $location.path("/");
                        }

                    }
                })
        };
    })
.factory("UserSerice",function($q,$http,ajax){
    var _url = '/api/v1/user/';

    return {
        get:function(id,param){
            var defer = $q.defer();
            $http.get(ajax.parseParam(_url + id,param))
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        save:function(param){
            var defer = $q.defer();
            $http.post(_url,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        },
        put:function(id,param){
            var defer = $q.defer();
            $http.put(_url + id,param)
                .success(function(data){
                    defer.resolve(data);
                })
                .error(function(data){
                    defer.reject(data);
                })
            return defer.promise;
        }

    }
})
//用户权限校验
.factory("auth", function (cookieUtils) {
    var auth = '';
    return {
        set: function (a) {
            auth = a;
            cookieUtils.set('auth',typeof a == "string" ? a : '');
        },
        get: function () {
            return auth;
        },
        del:function(){
            auth = '';
            cookieUtils.del('auth');
            cookieUtils.del('user_name');
            cookieUtils.del('user_pwd');
        }
    }
})

 

 

 

 

 

AngularJS中$http、$httpProvider、$resource操作笔记

1.设置httpProvider头

var app = angular.module(“Myapp”, [‘ngRoute’])
.config([‘$locationProvider’,’apikey’,function($locationProvider,apikey){
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix(“!”)
}])
.config(function ($routeProvider,$httpProvider) {
//设置http头
$httpProvider.defaults.headers.common[“X-Response-Code-By”] = “Angular1.3.8″;

AngularJS服务factory,service,provider,value,constant

AngularJS服务

AngularJS提供了一些内置服务,在任何地方使用它们的方式都是统一的。同时,为复杂应用创建我们自己的服务也是非常有用的。

在AngularJS中创建自己的服务是非常容易的:只需要注册这个服务即可。服务被注册后,AngularJS编译器就可以引用它,并且在运行时把它当作依赖加载进来。服务名称的注册表使得在测试中伪造和剔除相互隔离的应用依赖变得非常容易。

注册一个服务

.factory(“testFac”,function(){
return{
getA:function(a){
return a;
},
getB:function(b){
c(b)
}
}
})

其中这个服务包含了2个方法,只需要在控制器中引用testFac就可以直接使用这2个方法,就可以了;这只是一次服务演示。当然,这2个方法是非常枯燥无味的;但是,假设你需要对用户信息进行验证,或者你需要读取用户的一些信息,那么这个服务就不枯燥无味了。

angularJS学习笔记

QQ截图20160929161813

<script>
    function c(str) {
        console.log(str)
    }

    var app = angular.module("Myapp", ['ngRoute'])
            .config(['$locationProvider',function($locationProvider){
                $locationProvider.html5Mode(false);
                $locationProvider.hashPrefix("!")
            }])
            .config(function ($routeProvider) {

                $routeProvider
                        .when('/', {
                            templateUrl: 'views/main.html',
                            controller: 'MainCtrl'
                        })
                        .when('/about', {
                            templateUrl: 'views/about.html',
                            controller: 'AboutCtrl',

                        })
                        .when('/action', {
                            templateUrl: 'views/action.html',
                            controller: 'ActionCtrl'
                        })
                        .when('/contact:q', {
                            templateUrl: 'views/contact.html',
                            controller: 'ContactCtrl'
                        }).when("/register", {
                            templateUrl: 'views/register.html',
                            controller: 'registerCtrl'
                        })
                        .otherwise({
                            redirectTo: '/'
                        })
            })
            .run(['$rootScope','$location',function ($rootScope,$location) {
                $rootScope.title = "网站的标题";
                $rootScope.keywords = "网站的关键词";
                $rootScope.description = "网站的描述";

                //路由开始
                $rootScope.$on('$routeChangeStart',function(evt, next, current){

                });

                //路由成功
                $rootScope.$on('$routeChangeSuccess', function(evt, next, previous) {

                });

                //路由错误
                $rootScope.$on('$routeChangeError', function(current, previous, rejection) {
                    c('$routeChangeError')
                    c(current)
                    c(previous)
                    c(rejection)
                });

            }])
            .factory('myFactory', function(){
                var service = {1:"a",2:"b",3:"c"};
                return service;
            })
            .directive('myDirective', function(){
                return {
                    template: '<button>Click me</button>'
                }
            })
            .directive('ensureUnique', function ($http) {
                return {
                    require: 'ngModel',
                    link: function (scope, ele, attrs, cfg) {
                        scope.$watch(attrs.ngModel, function () {
                            $http({
                                method: 'POST',
                                url: '/1.php',
                                params: {filed: attrs.name, value: attrs.ngModel, value2: ele[0].value}

                            }).success(function (data, status, headers, fg) {
                                c(data);

                            }).error(function (data, status, headers, fg) {
                                alert('网络繁忙!');
                            })
                        });
                    }
                };
            })

            .controller('MainCtrl', function ($scope, $routeParams) {
                $scope.context = "Main页面标题";
                $scope.add = function (num) {
                    ++num;
                    alert("num:" + num);
                };
                $scope.name = {name: "a001", pwd: "a123456"};

            })
            .controller('AboutCtrl', function ($scope, $routeParams, $filter) {
                $scope.context = "关于我们";
                $scope.other = "谢谢支持!";

//

                //$scope.name = $filter('lowercase');
                $scope.unClock = function () {
                    $scope.isDisabled = true;
                    // alert('ok');
                }
                $scope.myChange = function (d) {
                    c(d);
                }
                $scope.submitForm = function (d) {
                    c(d);
                }

                $scope.people = [
                    {name: "小A", city: "重庆"},
                    {name: "小b", city: "成都"},
                    {name: "小c", city: "武汉"},
                    {name: "小d", city: "广州"},
                    {name: "小e", city: "上海"}
                ];

                $scope.fields = [
                    {isRequired: true, name: "user_name", placeholder: "请输入用户名", model1: "", msg: "请输入用户名"},
                    {isRequired: true, name: "user_pwd", placeholder: "请输入用户密码", model1: "", msg: "请输入用户密码"},
                    {isRequired: true, name: "email", placeholder: "请输入用户邮箱", model1: "", msg: "请输入用户邮箱"},
                ]
                $scope.cx = "testcx"


            }).controller('ActionCtrl', function ($scope, $routeParams) {
                $scope.context = "Action测试页面";


            }).controller('ContactCtrl', function ($scope, $routeParams) {
                $scope.context = "联系人";


            }).controller("nowDae", function ($scope) {

                $scope.now = new Date();
                $scope.do = function () {

                    $.ajax({
                        url: '/1.php',
                        type: 'post',
                        dataType: 'json',
                        async: false,
                        data: {id: 10, user_name: 'a001', user_pwd: '123456'},
                        success: function (data) {
                            c("data>>>>>");
                            c(data);
                        }
                    })
                }

            }).controller("registerCtrl", function ($scope, $routeParams) {
                $scope.context = "用户注册";
                $scope.showAgreement = function () {
                    alert("用户协议...");
                };

                $scope.doreg = function () {

                    alert('sdaf');
                    return false;
                }


            })
            .filter('number2', function () {
                return function (input) {

                    return "过滤过的:" + input;


                };
            }).filter('email2', function () {
                return function (input) {
                    if (input) {
                        return "filter:" + input;
                    }

                };
            })



</script>

代码包下载:百度网盘

http://pan.baidu.com/s/1kUH1H0F

1567899
 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |