角度6防护罩可观察悬挂

时间:2018-10-10 20:54:31

标签: angular rxjs observable guard

首先,我创建了2个守护程序,以检查用户是否在未导航到登录路线的情况下登录

这是代码

    import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../auth/authentication.service';
import { Router } from '@angular/router';
import { tap, map, take } from 'rxjs/operators';
import {of} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class IsUserGuard implements CanActivate {
  constructor( private auth:AuthenticationService, private router:Router){}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this.auth.user$.pipe(
      take(1),
      map(user => !!user),
      tap(isAuthenticated => {
          if(!isAuthenticated){
            console.log('must login');
            this.router.navigate(['/login']);
          }
      })
    )


  }
}

所以,它工作得很好,但是第二个防护中的问题我检查了用户登录是否不允许他再次浏览登录路由,所以我创建了该防护

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import { AuthenticationService } from '../auth/authentication.service';
import { tap, take, map, } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class IsGuestGuard implements CanActivate {
  constructor(private router:Router, private auth:AuthenticationService){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      return this.auth.user$.pipe(
        take(1),
        map(user => !!user),
        tap(isAuthenticated => {

        if(isAuthenticated){
          console.log('not a allow')
          this.router.navigate(['']);
        }
        else{
          console.log('allowe to show')
          return true
         //return of(true) give me the same resault
        }
        }),
      )
  }
}

它正在工作并且控制台打印“允许显示”,但是该页面没有出现,所以我觉得我处于循环中不要停止,如果我返回true而不是我的代码在第二个守护页面中工作

这也是路线代码

    const routes: Routes = [
    {
        path: '',
        component: PagesComponent,
        canActivate:[IsUserGuard],
        children: [
            {
                path: '',
                loadChildren: './components/dashboard/dashboard.module#DashboardModule'
            },
        ]
    },
    {
        path: 'login',
        canActivate: [IsGuestGuard],
        loadChildren: './auth/auth.module#AuthModule',
    },
    {
        path: '404',
        component: ErrorPageComponent
    },
    {
        path: 'error/:type',
        component: ErrorPageComponent
    },
];

此代码在帮助人员@JeffFairley @ fan-cheung之后起作用,谢谢大家

export class IsGuestGuard implements CanActivate {
  constructor(private router:Router, private auth:AuthenticationService){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      return this.auth.user$.pipe(
        map(isAuthenticated => {

          if(isAuthenticated){
            this.router.navigate(['/']);
            return false
          }

            return true
        })
      )

  }
}

1 个答案:

答案 0 :(得分:2)

布尔值已由map(user=>!!user)返回,tap是副作用运算符。尝试用map()替换水龙头,并返回正确的值,看看它是否有效。

 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      return this.auth.user$.pipe(
        take(1),
        map(user => !!user),
        map(isAuthenticated => {

        if(isAuthenticated){
          console.log('not a allow')
          this.router.navigate(['']);
            return false
        }

          console.log('allowe to show')
          return true
         //return of(true) give me the same resault

        }),
      )
  }