在这里遇到了一个简单的基本登录问题。我的AuthService工厂内部包含以下代码(2个相关函数和一个本地变量):
var username = '';
function login(uname, upwd, utype) {
// create a new instance of deferred
var deferred = $q.defer();
$http({
method: 'POST',
url: '/root',
headers: {
'Content-Type': 'application/json'
},
data: {
username: uname,
password: upwd,
type: utype
}
}).success(function(data, status, headers, config) {
if (status === 200) {
user = true;
username = data.username;
usertype = data.usertype;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
.error(function(data, status, headers, config) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function getusername() {
return username;
}
我的控制器如下所示:
angular.module('smApp').controller('rootloginController', ['$scope', '$location', 'notificationFactory', 'AuthService',
function($scope, $location, notificationFactory, AuthService) {
$scope.submit = function() {
AuthService.login($scope.rEmail, $scope.rootPassword, 'root')
if (AuthService.isLoggedIn()) {
$location.url('/dashboard');
notificationFactory.success('Logged in as ' + rootEmail);
} else {
//ngNotifier.notifyError($scope.rEmail);
notificationFactory.error('Invalid username & password combination');
}
};
};
}]);
我在login()之后在if语句中调用我的getusername(),由于login有$ http发布,它是异步的,我认为我在这里碰壁。
因此,我的主要问题是,第一次单击总是给我错误消息,第二次单击使我登录。我假设这与承诺没有立即兑现并花费一些时间来执行有关。我想知道是否还有这个?我真的没有等待等待执行任何其他代码,因为这是一个登录页面,并且使用超时似乎不是执行此操作的正确方法。
在这种情况下,您需要使用Promise API。通过$http
服务进行的服务器调用返回一个Promise,该Prom允许绑定.success
和.error
方法。
该.then
方法可以被用作用于两个的简写.success
和.error
。它接受两种分别在成功和错误情况下执行的功能。在这些函数中返回promise可以将调用链接到服务器。
在大多数情况下,这足够了:
// In service
login: function () {
return $http.post('your:url').then( // `then` here is optional, but possible
function () {}, // update service values without having to involve the controller (and/or transform the response object)
function () {} // throw error log mesages
)
}
// In controller
$scope.submit = function () {
AuthService.login().then(
function () {
// success logic: redirect, assign scope variables, etc
},
function () {
// error logic: allow retry
}
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句