2014-02-14 63 views
0

我想將我的登錄邏輯移動到服務..但我不知道如何將登錄詳細信息傳遞給服務。AngularJS:通過變量服務

我:

$scope.login = function (login_username, login_password) { 
    $http.post('/login', {userName: login_username, password: login_password}).success(function(response) { 
     .... 
    }); 
}); 

我所試圖做的事:

有需要尋找細節,並獲取用戶的個人資料服務...

app.factory('userProfile', function($http) { 
    return { 
    getUserProfile: function() { 
     return $http.post('/login',{userName: userNameVar, password: passwordVar}); 
    } 
    }; 
}); 

...但替換userNameVarpasswordVar與用戶的詳細信息,當用戶點擊登錄

function appCtrl($scope, userProfile) { 
    $scope.login = function (login_username, login_password, rememberMe) { 
     userProfile.getUserProfile().success(function(profile) { 
      $scope.uProfile = profile; 
      console.log($scope.uProfile); 
     }); 
    }; 
}; 

我試着在userProfile.getUserProfile()插入{userName: login_username, password: login_password}userProfile.getUserProfile({userName: login_username, password: login_password})

+0

將服務注入控制器並調用服務功能。您可以在該函數調用中傳遞該參數。 –

回答

4

在服務更改getUserProfile功能:

app.factory('userProfile', function($http) { 
    return { 
    getUserProfile: function(userNameVar, passwordVar) { 
     return $http.post('/login',{userName: userNameVar, password: passwordVar}); 
    } 
    }; 
}); 

,然後你的位指示可看起來像:

function appCtrl($scope, userProfile) { 
    $scope.login = function (login_username, login_password, rememberMe) { 
     userProfile.getUserProfile(login_username, login_password).success(function(profile) { 
      $scope.uProfile = profile; 
      console.log($scope.uProfile); 
     }); 
    }; 
};