我有一个简单的Angular functional路由守卫,它从服务的Subject<boolean>属性中检索boolean值.警卫看起来像预期的那样工作,看起来是这样的:

export const isConfigValidGuard = () => {
  const configService = inject(ConfigService);
  const notificationService = inject(NotificationService);
  const router = inject(Router);

  configService.configValidation$.subscribe({
    next: (isValid) => {
      if (isValid) {
        return true;
      } else {
        notificationService.warn('invalid config, redirecting to home');
        return router.parseUrl('/home');
      }
    }
  });
};

我的问题是,我是否需要取消订阅configService.configValidation$,如果需要,如何取消订阅.同样,configService.configValidation$的类型是Subject<boolean>.

推荐答案

是的,您需要取消订阅或take(1),以防止内存泄漏.

你也可以避免手动订阅,让ANGLE为你处理,直接返回Observable

export const isConfigValidGuard = () => {
  const configService = inject(ConfigService);
  const notificationService = inject(NotificationService);
  const router = inject(Router);

  configService.configValidation$.pipe(
    map((isValid) => {
      if (isValid) {
        return true;
      } else {
        notificationService.warn('invalid config, redirecting to home');
        return router.parseUrl('/home');
      }
    })
  );
};

因为Subject已经包含boolean,所以我们可以返回它的值,并且只处理它是false的情况.

Angular相关问答推荐

为什么这个拦截器只在发送事件上触发,而不是在实际响应上触发?

尽管有模拟间谍实现,规范文件仍调用真正的服务

如何使用新的@for遍历Angular 为17的对象?

父母和子元素在17号角不保持同步

有Angular react 形式的输入用货币管

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

我应该对我想要在我的Angular 17+组件中显示的任何变量使用信号吗?

为什么动画只触发一次?

Angular 单位测试表

如何在Angular功能路由保护中取消订阅RxJs主题

对象中的值丢失 angular ngrx

角 12 固态继电器 |页眉页脚在加载程序到来之前显示

Subject.complete() 是否取消订阅所有听众?

可从 Angular2 中的

如何设置Angular 4背景图片?

缺少 .angular-cli.json 文件:Angular

即使 withCredentials 为真,Angular 也不会发送在 Set-Cookie 中收到的 Cookie

NgrxStore 和 Angular - 大量使用异步管道或在构造函数中只订阅一次

如何将一个组件放入Angular2中的另一个组件中?

动态添加/删除验证器