如何从$ http帖子对象返回一个值?

时间:2014-12-09 20:17:41

标签: javascript angularjs angular-http

在我的控制器中,我调用了一个记录用户的服务。

我希望服务向我的控制器报告登录是否成功。我尝试将return true放在我的success(..)函数中,但实际上并没有返回任何内容。

我的服务:

loginRsrc.factory('loginSrvc', ['$http', function($http){

    return {
        http: function(){
            $http({
                method: 'POST',
                url: "http://myproj.herokuapp.com/api/signIn",
                data: $.param({email: "joe.gino@gmail.com", password: "1234567"}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })
            .success(function(res){
                console.log("res:");
                console.log(res);
                return true;
            })
            .error(function(res){
                console.log("res");
                console.log(res);
            }); 
        }
    };

我的控制器

loginApp.controller('loginCtrl', ['$scope', '$state', 'loginSrvc', function($scope, $state, loginSrvc){

    $scope.loginForm = {};
    $scope.loginForm.email = "";
    $scope.loginForm.password = "";

    $scope.submit = function(){
        loginSrvc.http();

    // true? Then send user to other page

1 个答案:

答案 0 :(得分:1)

服务:

loginRsrc.factory('loginSrvc', ['$http', function($http){

return {
    http: function(){
        return $http({
            method: 'POST',
            url: "http://myproj.herokuapp.com/api/signIn",
            data: $.param({email: "joe.gino@gmail.com", password: "1234567"}),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })

    }
};

<强>控制器

loginApp.controller('loginCtrl', ['$scope', '$state', 'loginSrvc', function($scope, $state, loginSrvc){

$scope.loginForm = {};
$scope.loginForm.email = "";
$scope.loginForm.password = "";

$scope.submit = loginSrvc.http().then(function(response){
                  // your data will be available in "response.data"
                  //code for success/resolved promise. 
                },function(error){
                  // error object available in error variable
                  // your code for error/rejected promise.
               });