AngularJS路线和解决与新的Firebase身份验证 [英] AngularJS Routes and Resolve with new Firebase Auth

查看:133
本文介绍了AngularJS路线和解决与新的Firebase身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Auth系统中使用新的Firebase,并通过 resolves 限制我的 $ routeProvider

但是,我不是很理解。



这就是我所拥有的。在我的.config函数中,我正在定义路由并初始化Firebase。以下是我的配置块。

  $ routeProvider 
.when('/',{
templateUrl:'templates / dashboard.ejs ',
//解析,需要限制
})
.when('/ login',{
templateUrl:'templates / login.ejs'
} )

firebase.initializeApp(config);

我在新的文档网站上发现,这些函数可用于我的 .run()为角度块。

  .run(函数($ rootScope,$ location){

$ rootScope.authentication = firebase .auth();

/*firebase.auth().onAuthStateChanged(function(user){
if(user){
$ rootScope.user = user;
$ else $ {
$ root $ user $;
$ location $($ / (user){
$ rootScope.user = user;
} else {
$ rootScope。 user = false;
console.log('No User!');
$ location.path('/ login');
}
})

现在,我上面只是每隔一次发射 访问我的网站上的任何网址。所以我的问题是,我如何把我的.run()函数的内容,并使其成为我的routeProvider的解决方案,所以我可以再次限制路线。

使用旧的firebase,您可以像下面那样调用$ firebaseAuth(),并且有一个如下所示的routeChangeError函数。

  //在配置块中。 **旧的方式** 
$ routeProvider
.when('/',{
templateUrl:'templates / dashboard.ejs',
resolve:{
currentAuth:[$ firebaseAuth,function($ firebaseAuth){
var ref = new Firebase(fbUrl);
var authObj = $ firebaseAuth(ref);

return





$ b $

  // .run block ** old way ** 
.run(函数($ root $,$ location)$ $ $ $ $ $ $ $ $ $ =='AUTH_REQUIRED'){
console.log('auth required!');
$ location.path(/ login);
}
});
$)

这个不行了,因为你不再使用 $ firebaseAuth()。或者新的Firebase(fbUrl); $ b

UPDATE



我觉得这有点乱,但是再看看路线,我想出了这个。



在我的路线解决:

  .when('/' ,
templateUrl:'templates / dashboard.ejs',
resolve:{
userAuthenticated:[$ http,$ q,function($ http,$ q){
var deferred = $ q;
if(firebase.auth()。currentUser){
deferred.resolve();
} else {
deferred.reject() ;
console.log('Really!?');
}
return deferred.promise;
]]
}
})

然后一个简单的routeChangeError。



$ $ $ $ $ $ $ $ $ $ $($$ routeChangeError,function(event,current,previous,rejection){
alert(Not authorized);
})

唯一的问题是, deferred.promise返回undefined。它不会激活routeChangeError函数。即使我的 console.log()被调用。



这可能是因为 firebase.auth()。currentUser 在没有用户认证时返回null?已被重新命名为 $ waitForSignIn() $ requireSignIn

<您也可以使用 $ firebaseRefProvider 服务来配置您的数据库URL,以便自动配置 $ firebaseAuthService

  angular.module('app',['firebase'])
.constant('FirebaseDatabaseUrl','< ($ firebaseRefProvider,FirebaseDatabaseUrl,$ routeProvider){
$ firebaseRefProvider.registerUrl(FirebaseDatabaseUrl);
。 );
$ routeProvider.when(/ home,{
controller:HomeCtrl,
templateUrl:views / home.html,
r esolve:{
//直到$ waitForSignIn解析
firebaseUser:function($ firebaseAuthService){
return $ firebaseAuthService。$ waitForSignIn(); (/账户,{
控制器:AccountCtrl,
templateUrl:views / account.html,$

}
} b $ b resolve:{
//控制器不会被加载,直到$ requireSignIn解析
firebaseUser:function(Auth){
//如果promise被拒绝,它会抛出$ stateChangeError
return $ firebaseAuthService。$ requireSignIn();
}
}
});
});

函数HomeController($ scope,$ firebaseRef,firebaseUser){

}


I am trying to use the new Firebase with the Auth system and restricting routes in my $routeProvider via resolves.

However, I'm not quite understanding.

This is what I have. In my .config function, I am defining routes and initializing firebase. The following is in my config block.

$routeProvider
   .when('/', {
      templateUrl: 'templates/dashboard.ejs',
      //resolve. this needs restricted
   })
   .when('/login', {
      templateUrl: 'templates/login.ejs'
   })

firebase.initializeApp(config);

I have found on the new docs site that these functions are available that are listed in my .run() block for angular.

.run(function($rootScope, $location) {

    $rootScope.authentication = firebase.auth();

    /*firebase.auth().onAuthStateChanged(function(user) {
        if(user) {
            $rootScope.user = user;
        } else {
            $rootScope.user = false;
            $location.path('/login')
        }
    })*/

    var user = firebase.auth().currentUser;

    if (user) {
        $rootScope.user = user;
    } else {
        $rootScope.user = false;
        console.log('No User!');
        $location.path('/login');
    }
})

Now, what I have above is only firing every other time I access any url on my site.

So my question is, how do I take what's in my .run() function and make it into a resolve for my routeProvider so I'm able to restrict routes again.

With the old firebase you would just call $firebaseAuth() like below and have a routeChangeError function that was called like the following.

// In config block. **old way**
$routeProvider
        .when('/', {
            templateUrl: 'templates/dashboard.ejs',
            resolve: {
                "currentAuth": ["$firebaseAuth", function($firebaseAuth) {
                    var ref = new Firebase(fbUrl);
                    var authObj = $firebaseAuth(ref);

                    return authObj.$requireAuth();
                }]
            }
        })

And then the routechangeerror in the .run() block.

 // .run block **old way**
 .run(function($rootScope, $location) {
    $rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) {
        if (eventObj === 'AUTH_REQUIRED') {
            console.log('auth required!');
            $location.path("/login");
        }
    });
})

This doesn't work anymore because you aren't using $firebaseAuth() anymore. or new Firebase(fbUrl); for that matter either.

UPDATE

I feel like it's a bit messy but looking into routes a little more, I came up with this.

In my route resolve:

.when('/', {
            templateUrl: 'templates/dashboard.ejs',
            resolve: {
                userAuthenticated: ["$http", "$q", function($http, $q) {
                    var deferred = $q;
                    if(firebase.auth().currentUser) {
                        deferred.resolve();
                    } else {
                        deferred.reject();
                        console.log('Really!?');
                    }
                    return deferred.promise;
                }]
            }
        })  

And then a simple routeChangeError.

$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
        alert("Not authorised");
})

The only problem is, it appears the deferred.promise is returning undefined. It's not activating the routeChangeError function. Even though my console.log() is getting called.

Could this be because firebase.auth().currentUser returns null when no user is authenticated?

解决方案

The methods have been renamed to $waitForSignIn() and $requireSignIn.

You can also use the $firebaseRefProvider service to configure your Database URL so it automatically configures the $firebaseAuthService.

angular.module('app', ['firebase'])
  .constant('FirebaseDatabaseUrl', '<my-firebase-url>')
  .controller('HomeCtrl', HomeController)
  .config(function($firebaseRefProvider, FirebaseDatabaseUrl, $routeProvider) {
     $firebaseRefProvider.registerUrl(FirebaseDatabaseUrl);
     $routeProvider.when("/home", {
        controller: "HomeCtrl",
        templateUrl: "views/home.html",
        resolve: {
          // controller will not be loaded until $waitForSignIn resolves
          "firebaseUser": function($firebaseAuthService) {
            return $firebaseAuthService.$waitForSignIn();
          }
        }
      }).when("/account", {
        controller: "AccountCtrl",
        templateUrl: "views/account.html",
        resolve: {
          // controller will not be loaded until $requireSignIn resolves
          "firebaseUser": function(Auth) {
            // If the promise is rejected, it will throw a $stateChangeError
            return $firebaseAuthService.$requireSignIn();
          }
        }
      });
  });

function HomeController($scope, $firebaseRef, firebaseUser) {

} 

这篇关于AngularJS路线和解决与新的Firebase身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆