我有一个名为Auth的工厂,其方法Auth.signIn()
通过我的解耦API进行身份验证。该部分有效,我试图捕获响应,即用户信息。从我的控制器调用工厂工作,但我似乎无法捕获该方法的响应。
控制器
.controller('DashCtrl', function($scope, Auth) {
//OAUTH SIGN IN
$scope.signIn = function() {
$scope.currentUser = Auth.signIn()
//^^Auth.signIn() is happening but $scope.currentUser is undefined when I try to access it in the view
}
//OAUTH SIGN OUT
$scope.signOut = function() {
Auth.signOut()
}
})
工厂
.factory('Auth', function($auth) {
var user = null
return {
signIn: function() {
$auth.authenticate('google')
.then(function(response) {
return response //trying to catch this in the controller with currentUser = Auth.signIn()
//verified that response is the user data
})
.catch(function(resp) {
// handle errors
})
}
})
我是棱角分明的新人,所以任何帮助和指示都会受到赞赏。我试着用我的代码/问题尽可能简洁。提前感谢您的帮助。
答案 0 :(得分:1)
首先,在您工厂的signIn功能中,您应该返回承诺
signIn: function() {
return $auth.authenticate('google')
.then(function(response) {
return response.data;
});
}
然后在您的控制器中,在currentUser
Auth.signIn
初始化
$scope.signIn = function() {
Auth.signIn().then(function(data) {
$scope.currentUser = data;
}
}