我正在使用angularjs开发一个应用程序,这是我第一次使用angular。虽然,我已经开始理解它并开发了应用程序的某些部分,但我被困在一个特定的点上。
我正在尝试实现登录功能,因此当页面加载时,我正在对用户进行身份验证并将他重定向到登录页面。成功登录后,我将用户的一些值存储在其中一个配置提供程序中。
现在我正在使用一个 API,它有自己的身份验证方法,并且他们公开了我可以用来对用户进行身份验证的 ajax 方法。
我在下面提供了一个片段。我主要做的是使用外部 API,对用户进行身份验证,一旦经过身份验证,我就会使用 API 的另一个 ajax 方法(称为"GetUserDetails")获取与该用户关联的角色。
在"GetUserDetails"的响应中,我注入了一个提供程序并设置了一些值,因此我可以在我的应用程序中使用它。
这里的问题是 app.config 方法永远不会被调用/执行。我的意思是 ajax 请求正在返回响应,并且警报显示在我的页面上,但 app.config 从未执行。
但是同样的 app.config 如果我在 GetUser 方法的 done() 中调用,app.config 就会被执行并将值存储在我的提供程序中。但是我希望在应用程序中执行任何操作之前也存储 GetuserDetails 值,因为我想根据用户执行某些功能。
以下是我在主文件中的函数.js
function(angular,angularRoute,app,routes,configService){
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
$.c.authentication.getUser()
.done(function(response){
if(response.userName!="anonymous"){
$.c.ajax({
method: "GetUserDetails",
parameters: {
User: response.user
}
})
.done(function(res) {
alert("I have reached the destination").
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(true);
configServiceProvider.setUserName(response.userName);
configServiceProvider.setUserObject(response);
configServiceProvider.setUserRoleDetails(res);
}]);
})
.fail(function(res) {
alert("Error while getting user roles ."+res);
});
angular.resumeBootstrap([app['name']]);
}
else
{
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(false);
configServiceProvider.setUserName(response.userName);
}]);
//Show Login Screen
var url = window.location.href.split("#")[0];
window.location.href = url + "#/Login";
angular.resumeBootstrap([app['name']]);
}
})
.fail(function(response){
$rootScope.isLoggedIn=false;
});
});
这是我的配置服务提供商
define(['../app'],function(app){
return app.provider('configService', function(){
var options={};
this.setLoginStatus = function(status){
//$rootScope.isLoggedIn = status;
options.isLoggedIn=status;
};
this.setPreLoginInfo=function(info){
options.preLoginInfo=info;
};
this.setUserName=function(name){
options.username=name;
}
this.setUserObject = function(userObject) {
options.userObject = userObject;
}
this.setUserRoleDetails = function(userRoleDetails) {
options.userRoleDetails = userRoleDetails;
}
this.$get=[function(){
if(!options){
}
return options;
}];
});
})
谁能解释一下这里出了什么问题或我错过了什么?
另外,有没有其他选择来实现相同的功能?
运气弄清楚为什么上述情况不起作用。由于我已经花了很多时间,因此我找到了一种解决方法,可以在使用服务时实现相同的效果。