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

        });

    }

})

 

Leave a Comment