Angular7路由守卫CanActivate中从服务器端判断登录状态

最初不知道怎么返回一个httpClient得到的的可观察对象,因为无法从subscribe中返回observable,后来自己new了一个Observable,然后在里面再去调用obserber.next(),解决了这个问题。

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from '../auth.service';
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): Observable<boolean> {
    if (this.authService.isLogin) {
      return of(true)
    }
    else {
      var data = this.authService.checkLogin()
      //自己new一个可观察对象
      return new Observable<boolean>((obserber) => {
        data.subscribe(d => {
          if (d.Code === 1) {
            obserber.next(true)
          } else {
            obserber.next(false)
            this.router.navigateByUrl('/login');
          }
          obserber.complete();
        });
      })
    }
  }
}

你可能感兴趣的:(javascript)