如何在 Angular 路由防护中使用 Observable?

Aij*_*jaz 0 javascript angular angular-router-guards angular-router

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

 { path: '', redirectTo: 'home1', canActivate: [homepageGuard], pathMatch: 'full' },
  { path: 'home1', loadChildren: './lazyloadedmodule1' },
  { path: 'home2', loadChildren: './lazyloadedmodule2' },
  { path: 'home3', loadChildren: './lazyloadedmodule3' },
  { path: 'basehome', loadChildren: './lazyloadedmodule4' }
Run Code Online (Sandbox Code Playgroud)

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

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;
      }
    );
  }
Run Code Online (Sandbox Code Playgroud)

这就是我的服务在调用 API 时的样子。

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

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

Mac*_*cik 5

我提出这样的建议。使用服务并返回真/假并导航。

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))
    )
    }
  }
Run Code Online (Sandbox Code Playgroud)

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