代码之家  ›  专栏  ›  技术社区  ›  tilly

角度保护中的异步代码不会打开页面

  •  -2
  • tilly  · 技术社区  · 8 年前

    设置很简单。我有一个守卫守卫一条路线。如果用户的属性 locationSaved === true

    我做了服务器请求,它返回true,所以我希望它打开页面,但不幸的是它没有。我假设它与我在页面中执行的异步请求有关,因为当我用一个简单的 return true ; 然后它确实打开了页面。

    import { Injectable } from '@angular/core';
    import {ActivatedRouteSnapshot, CanActivate} from '@angular/router';
    import {AuthenticationService} from './auth.service';
    import {Observable} from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class LocationGuardService implements CanActivate {
    
      constructor(private authService: AuthenticationService) { }
    
      canActivate(route: ActivatedRouteSnapshot): boolean {
        console.log('entered the guard');
        if (this.authService.isLoggedIn()) {
          if (this.authService.currentUser().user.locationSaved) {
            return true;
          } else {
            this.authService.isLocationSaved()
              .subscribe((status: {saved: boolean}) => {
                console.log('saved', status);
                return status.saved;
              });
          }
        } else {
          return false;
        }
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   SiddAjmera    8 年前

    subscribe map ped至 status.saved

    当然,这个 canActivate boolean 或者一个 Observable<boolean> 激活 .

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, CanActivate } from '@angular/router';
    import { AuthenticationService } from './auth.service';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root'
    })
    export class LocationGuardService implements CanActivate {
    
      constructor(private authService: AuthenticationService) { }
    
      canActivate(route: ActivatedRouteSnapshot): boolean | Observable<boolean> {
        if (this.authService.isLoggedIn()) {
          if (this.authService.currentUser().user.locationSaved) {
            return true;
          } else {
            return this.authService.isLocationSaved()
              .pipe(map(status => status.saved));
          }
        } else {
          return false;
        }
      }
    }