AngularJS:如何在用户通过身份验证之前隐藏模板内容? [英] AngularJS: How to hide the template content until user is authenticated?
问题描述
我的应用有 2 个页面:main.html
和 login.html
.当未通过身份验证的用户转到 /main
时,他们应该被重定向到 /login
.
My app has 2 pages: main.html
and login.html
.
When not authenticated users go to /main
they should be redirected to /login
.
问题是main.html
先被渲染,一秒左右,当用户认证失败时,login.html
被渲染.
The problem is that main.html
is rendered first, and after a second or so, when user authentication fails, login.html
is rendered.
如何防止 main.html
在身份验证成功之前呈现?
How could I prevent from main.html
to be rendered until authentication succeeds?
这是相关的代码(CoffeeScript):
Here is the relevant code (CoffeeScript):
angular.module('myApp', [...])
.config(['$routeProvider', ($routeProvider) ->
$routeProvider.when '/login',
templateUrl: 'html/login.html'
controller: LoginController
$routeProvider.otherwise
templateUrl: 'html/main.html'
controller: MainController
])
.run(['$rootScope', '$location', 'appService', ($rootScope, $location, app) ->
$rootScope.$on '$locationChangeStart', (event, newValue, oldValue) ->
return if newValue == '/login'
$.when(app.authenticate()).fail ->
$location.path '/login'
$rootScope.$apply()
])
<小时>
angular.module('myApp.services').factory 'appService' , () ->
rootRef = new Firebase('https://myapp.firebaseio.com')
user: null
authenticate: ->
deferred = $.Deferred()
authClient = new FirebaseAuthClient rootRef, (error, user) =>
if error
# An error occurred while attempting login
@user = null
deferred.reject()
else if user
# User authenticated with Firebase
@user = user
deferred.resolve()
else
# User is logged out
@user = null
deferred.reject()
deferred.promise()
推荐答案
好吧,在用户通过身份验证之前,我不会提供模板(在您的情况下为 main.html
).我在服务器上有一个用于提供模板的自定义功能,用于检查用户是否已通过身份验证.如果在函数中我发现用户未登录,它会返回带有 401 状态代码的响应.在 angular 代码中,我将请求保持到身份验证,然后再次请求模板.
Well, I don't serve the template (in your case main.html
) until the user is authenticated. I have a customized function on server for serving templates, which checks if the user is authenticated. If in the function I find out the user is not logged in, it returns response with 401 status code. In angular code I then hold the request until the authentication and then ask for the template again.
我的灵感来自这篇文章:http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
I was inspired to do this by this post: http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
这篇关于AngularJS:如何在用户通过身份验证之前隐藏模板内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!