【问题标题】:angular 6 guard Observable hanging角度 6 防护 可观察悬挂
【发布时间】:2018-10-11 21:03:46
【问题描述】:

首先我创建了 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
        })
      )

  }
}

【问题讨论】:

  • 您在两种情况下都打印相同的消息。更改 if 和 else 条件中的日志消息,并再次检查通过了哪些条件。
  • @SunilSingh 对不起,我复制了错误的代码,我又脸红了,还是一样
  • 您是否将两个 Guard 用于同一路由?如果是,那么这两个守卫都将处于永远循环中。为了更好地检查这一点,请将控制台日志放在开头。
  • 您的示例在tap() 中包含return true。您不能从 tap 返回,因为它不会转换数据。如果你打算转换数据,你应该使用map()Fan Cheung 回答相同。
  • @JeffFairley 它工作得很好,所以我也不应该使用点击地图来处理我想要做的事情并将值返回为布尔值

标签: angular rxjs observable guard


【解决方案1】:

map(user=&gt;!!user) 已经返回布尔值,tap 是一个副作用运算符。尝试用 map() 替换 tap 并返回正确的值,看看它是否工作。

 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

        }),
      )
  }

【讨论】:

  • 它工作得很好,所以保护标签在我的代码中没有用!我只使用一张地图而不是两张地图,并且在地图内部处理数据并运行我想要的并最终返回布尔值
猜你喜欢
  • 2021-10-25
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2017-05-23
  • 1970-01-01
  • 2019-04-27
  • 2019-07-26
相关资源
最近更新 更多