我正在Angular(ui-router)&中创建一个上传页面。 Firebase应用,并希望上传页面仅供登录用户使用。我们的想法是,如果匿名(已注销/未注册)用户尝试访问上传网址example.com/upload
,则会将其发送至example.com/posts
。
我尝试通过在 upload.ctrl.js 控制器中编写if语句来检查用户是否已注销以及用户是否确实已注销,我尝试通过在Angular中执行此操作$location
服务将/posts
的路径更改为我的应用的根网址,如下所示:
if(Auth.logout) {
$location.path('/posts');
// Added the following line for feedback in console
console.log('Auth.logout is true');
}
但是,如果用户登录并导航到/upload
, upload.tpl.html 模板将正常加载,但该网址将切换为/posts
/upload
。只有在用户注销时才会发生此操作,但即使用户已登录也会发生此操作。
我在if语句中添加的行console.log('Auth.logout is true');
中找到了线索。我不确定为什么,但只要我在登录或注销时尝试导航到/upload
,它就会被调用两次。似乎Auth.logout
始终为真,这就是为什么当我尝试转到/posts
时,网址始终位于/upload
。
我创建了一个在这里演示此问题的Plunker
http://plnkr.co/edit/jx7xuyqxs3dPfQqTms6C?p=preview
您可以在单独的窗口中启动它以查看URL更改(或在此情况下不更改)。
要登录,您可以使用:
有关如何解决此问题的任何想法?提前谢谢。
在Plunkr正在运行时,手动将URL更改为/upload
复制并粘贴http://run.plnkr.co/ZzrkWWeRl32wZsQ2/#/posts到新的浏览器选项卡中(他们为您构建的单独窗口不允许您更改URL)在新选项卡中运行后,您可以手动将URL更改为http://run.plnkr.co/ZzrkWWeRl32wZsQ2/#/upload(登录或注销时),以查看URL将如何更改回{{3} }
我能够通过更改if语句条件来解决这个问题
if(!Auth.user) {
$location.path('/posts');
}
如果Auth.user
存在且为真,那么该用户是真实的。
upload.ctrl.js
app.controller('UploadCtrl', function ($scope, $stateParams, $location, Auth) {
$scope.signedIn = Auth.signedIn;
$scope.logout = Auth.logout;
if(Auth.logout) {
$location.path('/posts');
console.log('Auth.logout is true');
}
});
auth.serv.js
app.factory('Auth', function ($firebaseSimpleLogin, FIREBASE_URL, $rootScope, $firebase) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
login: function (user) {
return auth.$login('password', user);
},
logout: function () {
auth.$logout();
},
resolveUser: function() {
return auth.$getCurrentUser();
},
signedIn: function() {
return !!Auth.user.provider;
},
user: {}
};
$rootScope.$on('$firebaseSimpleLogin:login', function(e, user) {
angular.copy(user, Auth.user);
Auth.user.profile = $firebase(ref.child('profile').child(Auth.user.uid)).$asObject();
console.log(Auth.user);
});
$rootScope.$on('$firebaseSimpleLogin:logout', function() {
console.log('logged out');
if(Auth.user && Auth.user.profile) {
Auth.user.profile.$destroy();
}
angular.copy({}, Auth.user);
});
return Auth;
});
答案 0 :(得分:1)
此前是upload.ctrl.js
if(Auth.logout) {
// this is reason why it goes to posts
$location.path('/posts');
console.log('Auth.logout is true');
}
我们可以看到,支票是 if(Auth.logout)
。由于 logout是一个函数,因此该语句始终返回true。这意味着,我们总是去 $location.path('/posts');
这是更新版本,请在退出结束时查看 ()
: if(Auth.logout())
if(Auth.logout()) { // function call
$location.path('/posts');
console.log('Auth.logout is true');
}
检查here