Angular的CanActivate守卫如何等待API响应而不需要每次都调用API?
创始人
2024-10-24 02:00:32
0

可以使用RxJS中的operator,比如switchMap()来实现等待API响应并且避免重复调用API的问题。具体实现方式可以参考下面的代码示例:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean {
    return this.auth.getUser().pipe(
      switchMap(user => {
        if (user) {
          return Observable.of(true);
        } else {
          this.router.navigate(['/login']);
          return Observable.of(false);
        }
      })
    );
  }
}

在上面的代码中,AuthGuard是一个CanActivate的守卫,其实现了等待API响应并且避免重复调用API的问题。具体来说,在canActivate()方法中,我们使用了switchMap()运算符来等待getUser()方法返回的Observable对象,并根据用户是否存在来返回一个Observable对象。如果用户存在,则返回true;如果用户不存在,则导航至登录页面,并返回false。

这种使用RxJS的做法可以大大简化代码,并减少对API的不必要调用,提高页面的运行效率。

相关内容

热门资讯

现场直击"菠萝辅助器... 现场直击"菠萝辅助器免费版的特点"aapoker透视脚本(竟然是真的辅助修改器)-哔哩哔哩1、下载好...
透视曝光"pokem... 透视曝光"pokemmo手机脚本辅助器"切实真的是有辅助挂(哔哩哔哩)1、超多福利:超高返利,海量正...
目前来看"wepok... 目前来看"wepoker轻量版透视方法"pokermaster辅助器(总是是真的辅助工具)-哔哩哔哩...
透视开挂"wepok... 透视开挂"wepoker有透视功能吗"本来是有辅助技巧(哔哩哔哩)1、玩家可以在wepoker有透视...
透视总结"智星德州可... 透视总结"智星德州可以透视吗"wepoker辅助工具(果然是真的辅助下载)-哔哩哔哩1、起透看视 智...
透视解密"wepok... 您好,wepoker透视挂底牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
透视软件"hhpok... 透视软件"hhpoker德州机器人"拱趴大菠萝万能辅助器(切实真的有辅助平台)-哔哩哔哩1、很好的工...
透视必备"wepok... 透视必备"wepoker破解器有用吗"好像有辅助教程(哔哩哔哩)该软件可以轻松地帮助玩家将wepok...
透视真的"werpl... 透视真的"werplan有挂吗"拱趴大菠萝辅助神器(其实真的有辅助软件)-哔哩哔哩;所有人都在同一条...
透视解谜"wepok... 透视解谜"wepoker辅助器软件下载"确实真的有辅助攻略(哔哩哔哩)运wepoker辅助器软件下载...