AngularJS的新手。我想使用登录页面,使用控制器(我称其为“ AccessCtrl”)和服务来构建一个简单的登录屏幕。
我希望控制器使用服务(我称其为“ AuthService”),该服务将执行验证用户名/密码的REST调用,并且还将包含有关该登录尝试成功或失败的信息。
我想接收有关上次登录尝试的信息(由REST调用返回)。现在-仅是我想在登录屏幕上显示的字符串(例如“密码无效”或“帐户已过期”或“欢迎”)。我将其设为希望显示的AuthService服务的属性。
我的观点是,有一个包含用户名,密码和提交按钮的表单,该按钮调用了控制器的login()方法。为了简洁起见,此处不包括在内。我不认为这就是问题所在。
首先,我想捕获服务器何时关闭/不可用等情况,并使用相同的服务报告此情况。首先-所有呼叫都会失败,(因为我的网址无效)。
控制器的定义如下:
angular.module('loginApp')
.controller('AccessCtrl', ['$scope','$http','AuthService',
function ($scope,$http,AuthService,Config) {
this.login =function() {
var user={user:this.username,password:this.password,otherCredentials:this.otherCredentials} ;
AuthService.login(user);
this.message=AuthService.message;
};
}]);
我的工厂服务定义如下:
.factory('AuthService', ['$http', function ($http) {
var authService = {};
var apiRootUrl="http://somesite.com/urany";
authService.login = function (credentials) {
authService.message="";
$http.post(apiRootUrl+'/login', credentials)
.then(
function (response) {
// populate OK message
authService.message="Welcome !";
},
function (response) {
// Currently - all calls fail, as the URI is invalid
// I want to trap this.
authService.message = "Server unavailable with response status = " + response.status ;
return authService;
},
function(response) {
// this is the notify callback function.
//
});
};
authService.isAuthenticated = function () {
// rerurn true or false if previously authenticated
return true;
};
return authService;
}])
;
问题是我的无效消息(“服务器不可用,响应状态...”)没有出现在我的视图中。
在单步执行代码时,将调用正确的authService函数,但是似乎未将其填充到控制器/视图中。
我感觉这是一个时序问题,正在执行的控制器
this.message=AuthService.message;
在电话真正从帖子中回来之前-但是我不确定情况是否如此或如何解决。
任何帮助/线索欢迎。
谢谢。
小号
你尝试过这样的事情吗?
角度服务代码:
//call the service
AuthService.login(user).then(function(response){//begin call back
//store the response data message object property returned from the service
$scope.message = response.message;
}//end call back
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句