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中$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″;

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