如果没有使用 AngularFire 2 登录,则重定向到登录页面

Redirect to login page, if not logged in with AngularFire 2

如果用户未通过 Angular2 / AngularFire2 进行身份验证,将用户重定向到登录页面的最佳方法是什么?

例如;我想保护 /dashboard 页面免受未经身份验证的用户的影响。用户应该立即被重定向到 /login 页面,

我正在使用

这里可以使用Auth方式

if ($scope.auth === null) {
  $state.go('login');
}

注入您的 $firebaseAuth 并将其分配给 $scope.auth 然后让 if 检查其真假

找到解决方案。

感谢来自 r-park

todo-angular-2
import { ReflectiveInjector } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { AuthService } from './auth-service';


let appInjector: ReflectiveInjector;

/**
 * This is a workaround until `CanActivate` supports DI
 * @see https://github.com/angular/angular/issues/4112
 */

export class AuthRouteHelper {
  static dependencies(): {auth: AuthService, router: Router} {
    const injector: ReflectiveInjector = AuthRouteHelper.injector();
    const auth: AuthService = injector.get(AuthService);
    const router: Router = injector.get(Router);
    return {auth, router};
  }

  static injector(injector?: ReflectiveInjector): ReflectiveInjector {
    if (injector) appInjector = injector;
    return appInjector;
  }

  static requireAuth(): boolean {
    const { auth, router } = AuthRouteHelper.dependencies();
    if (!auth.authenticated) router.navigate(['/SignIn']);
    return auth.authenticated;
  }

  static requireUnauth(): boolean {
    const { auth, router } = AuthRouteHelper.dependencies();
    if (auth.authenticated) router.navigate(['/Tasks']);
    return !auth.authenticated;
  }
}

您可以使用 Angular 2 的 UI 路由器保护条件来保护 url。 https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

一个使用 firebase 的例子

保护组件

请注意,最好将此处的引用 AF 替换为身份验证服务。

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AngularFire } from 'angularfire2';

@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
    user;
    constructor(private af: AngularFire, private router: Router) {
        this.af.auth.subscribe(user => {
            if (user) {
                this.user = user;
            } else {
                this.user = undefined;
            }
        });
    }

    canActivate() {
        if (this.user) {
            return true;
        }
        this.router.navigate(['/login']);
        return false;
   }
}

申请途径

import { CanActivateViaAuthGuard} from './CanActivateViaAuthGuard';

const routes: Routes = [
    {path: '/Login', component: LoginComponent},
    {path: '/dashboard', component: DashboardComponent, canActivate: [CanActivateViaAuthGuard]}
];

export const routing = RouterModule.forRoot(routes);

最后是登录码

onSubmit() {
    this.af.auth.login({
      email: this.email,
      password: this.password,
    }).then(() => {
      this.submitted = true;
      this.router.navigate(['/dashboard', this.dashboard]);
    });
  }