将 canActivate Angular 与 AngularFirebase2 一起使用

Using canActivate Angular with AngularFirebase2

我已经阅读并尝试了一万亿条建议。

大约 2 年前,我在 Angular 中使用 AngularFire2 做了 Auth Guard,如下所示:

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.af.auth.subscribe((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        this.allowed = false;
      } else {
        this.allowed = true;
      }
    })
    return this.allowed;
  }

今天,我正在尝试使用今天的 javascript

复制相同的 auth guard
Angular CLI: 7.3.2
Node: 11.10.0
OS: linux x64
Angular: 7.2.5
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router, service-worker

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.13.2
@angular-devkit/build-angular     0.13.2
@angular-devkit/build-optimizer   0.13.2
@angular-devkit/build-webpack     0.13.2
@angular-devkit/core              7.3.2
@angular-devkit/schematics        7.3.2
@angular/cli                      7.3.2
@angular/fire                     5.1.1
@angular/pwa                      0.12.4
@ngtools/webpack                  7.3.2
@schematics/angular               7.3.2
@schematics/update                0.13.2
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.29.0

我知道 rxjs 发生了一些变化,所以像这样

this.af.auth.subscribe((auth) => {

现在变成了

this.af.authState.pipe(map(auth) => {

除了执行上述操作会导致浏览器选项卡挂起。

我已经看到至少 15 个关于如何使用 AngularFirebase 进行路由保护的不同问题,他们都采用了不同的方法。

我知道未来几个月事情会发生变化(很可能)如何做到这一点,但截至 2019 年,2 月 18 日,您如何使用 AngularFire2 进行路由保护?

编辑

这是 interesting/weird 的来源。我在下面尝试了@sergey-mell 的回答。

这是我在路线

中应用authGuard的方式
const routes: Routes = [
  { path: 'auth', loadChildren: './auth/auth.module#AuthModule' },
  {
    path: '',
    component: MenuComponent,
    children: [
      { path: '', component: HomeComponent },
      { path: 'new', component: NewcustomerComponent },
      { path: ':customer_id', component: CustomerdetailComponent }
    ],
    canActivate: [AuthGuard]
  }
];

发生的情况是,如果没有登录,我直接在浏览器中访问,localhost:4200/,浏览器挂了。

在控制台中,Chrome通知我访问下面的URL

https://crbug.com/882238

我关注 link,但我被告知我没有查看该错误的权限。困扰我的错误。好的。

我是不是遗漏了什么?

前言:

  1. 如果通过 Angular docs Guard 可以 return 解析为 boolean.
  2. 的 Observable
  3. AngularFire docs 表明我们可以使用 AngularFireAuth.user observable 来检查用户身份验证状态。

所以,对我来说,你的守卫应该是这样的:

@Injectable()
class LetMeInGuard implements CanActivate {
  constructor(private afAuth: AngularFireAuth,
              private routes: Router) {}

  canActivate(route: ActivatedRouteSnapshot, 
              state: RouterStateSnapshot): Observable<boolean> {
    return this.afAuth.user.pipe(
      map(user => {
         if (!user) {
             this.router.navigate(['/login']);
         }
         return !!user;
      })
    );
  }
}