如何在 Angular 路由保护中使用 Observable? [英] How to use an Observable in Angular route guard?

查看:22
本文介绍了如何在 Angular 路由保护中使用 Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度路由模块中,我在默认主页时使用基本导航,现在在某些情况下,我想决定要导航的路线.这就是我的应用路由的样子.

In my angular routing module, I am using a base navigation when its the default homepage, now on some condition, I want to decide which route to navigate. This is how my app routing looks.

 { path: '', redirectTo: 'home1', canActivate: [homepageGuard], pathMatch: 'full' },
  { path: 'home1', loadChildren: './lazyloadedmodule1' },
  { path: 'home2', loadChildren: './lazyloadedmodule2' },
  { path: 'home3', loadChildren: './lazyloadedmodule3' },
  { path: 'basehome', loadChildren: './lazyloadedmodule4' }

现在在我的路线守卫中,我像这样调用订阅.

Now in my route guard, I am calling the subscription like this.

canActivate(): Observable<any> | boolean {
    return this._myService.getCurrentApp().subscribe(
      (r) => {
        if(r === 'app1'){
          //navigate to app1homepage
        } else if (r === 'app2') {
          //navigate to app2homepage
        } else {
          // navigate to base homepage
        }
      },
      (e) => {
        console.log(e);
        return false;
      }
    );
  }

这就是我调用 API 时我的服务的外观.

This is how my service looks where I call the API.

public getCurrentApp(): Observable<any> {
    return this.http.get(this.apiBaseUrl + 'getApp').pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(err.error.errorMessage);
      }));
  }

首先,routeguard 不会将该值作为订阅,因为我相信它只需要一个布尔值,但我会以字符串形式返回响应.我如何确保在第一个页面加载期间调用 API 并相应地重定向它?

Firstly the routeguard is not taking the value as subscription, because I believe its expecting just a boolean, but i will be getting the response as string back. How do I make sure that during the first page load, its calling the API, and redirecting it accordingly?

推荐答案

我提出这样的方案.使用服务并返回true/false &导航.

I propose something like this. Use service and return true/false & navigate.

canActivate(): Observable<any> | boolean {
return this._myService.getCurrentApp()
    pipe(
        tap((response) => {
            if(r === 'app1'){
                this.router.navigate([...]);
            } else if (r === 'app2') {
                this.router.navigate([...]);
            } else {
                this.router.navigate([...]);
            }
        }),
        map(() => false),
        catchError((e)=> of(false))
    )
    }
  }

坦率地说,这不是此类问题的最佳解决方案.我相信更好的方法是为不同的路径创建不同的 AuthGuard,这将执行 API 请求并检查是否允许去特定的路由.然后只返回 false 或 true.

Frankly writing, that's not the best solution for such issue. I believe that a better approach would be to create different AuthGuards for the different path which will do API request and check if it is allowed to go to a specific route. Then only return false or true.

这篇关于如何在 Angular 路由保护中使用 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆