angular - 为 Angular Router Guard 处理多个 Observable
问题描述
我是 RxJS 的新手,但似乎符合我的需求。
我想知道是否可以检索
Observable
that listen twoBehaviorSubject
。
首先我使用 Angular 10 !
我在用
- 调用我的组件的服务创建一个检索用户数据的承诺
- 特定路线上的警卫,也使用先前的服务来确定访问权限。
为了更好地理解这里是我的配置:
// auth.guard.ts
import { Injectable } from '@angular/core';
import {... } from '@angular/router';
import { from, Observable, Subscription } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild {
constructor(private auth: AuthService) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> {
return from(this.auth.canActivate());
}
}
//app-routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SecuredComponent } from './pages/secured/secured.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
// other paths
{
path: 'mes-formations',
component: SecuredComponent,
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
//auth.service.ts
import { Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject} from 'rxjs';
import { UrlTree } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService implements OnDestroy {
private userOk$ = new BehaviorSubject(false);
private isLoading$ = new BehaviorSubject(false);
constructor(args) {
this.authenticate();
}
async authenticate(): Promise<boolean | UrlTree> {
// set isLoading$ to true till user request ends
// fetch user and set userOk$ to true if succeed
}
async canActivate(): Observable<boolean | UrlTree> {
// return true if isLoading is false AND userOk$ true
// instead redirect outside app
}
}
我的目标是回答AuthGuard
这些条件:
- 如果
isLoading
为真 -> 等待 - 如果
isLoading
为假且为userOk
真 -> 真 - if
isLoading
为假且为userOk
假 -> 做其他事情
怎样才能做到这一点?谢谢大家!
解决方案
尝试利用combineLatest
、filter
和map
。
您可能希望从而不是isLoading$
.true
false
canActivate(): Observable<boolean> {
return combineLatest(
this.isLoading$,
this.userOk$,
).pipe(
filter(([isLoading, userOk]) => !isLoading), // wait until isLoading is false (filter emissions while isLoading is true)
map(([isLoading, userOk) => {
if (userOk) { // isLoading is false and userOk is true
return true;
} else { // isLoading is false and userOk is false
// do something else (do whatever else you want to do and return false)
return false;
}
})
);
}
推荐阅读
- c - 为什么在我运行我的 c 代码时显示错误“collect2.exe:错误:ld 返回 1 退出状态”
- linux - 打开文件过多错误,但 99.5% 的 inode 是免费的
- django - “函数”对象没有属性“对象”Django AttributeError
- c++ - 在 C++/Linux 中设置单调时钟的一些技巧
- postgresql - Postgres - 每当行满足特定条件时更新运行计数
- django - 如何在 Django 中显示最大折扣产品?
- python - discord.py - 删除用户频道权限和错误消息“你已经阻止了这个频道”
- javascript - 从谷歌驱动器下载文件时不允许使用 405 方法
- javascript - 获取文件并将 JavaScript 数组转换为 PHP 数组
- c++ - #define c-preprocessor constants ...我做错了什么?