我有这样的场景:我将查询参数保存在服务中,以便在用户关闭浏览器时保持此数据的活动状态,使用解析器我使用来自活动路由的结果将缺少的参数添加到组件的Init挂钩中,在某些组件中,此查询参数涉及到执行UI或服务操作.

照顾好它:

export const queryParamsResolver = (route: ActivatedRouteSnapshot) => {
  const productId = route.paramMap.get('id');

  if (!productId) {
    return of(undefined);
  }

  // is possible navigate from here instead of send the data the component and navigate from the componen
  return inject(CodeService).getQueryParamerts(+productId);
};

在下列航线上航行:

ngOnInit() {
    this.activatedRoute.data.subscribe(({ query }) => {
      // extra navigation is not required only provide query params to the current url
      this.router.navigate([], { queryParams: query });
    });
  }

可以使用更好的实现来处理某些组件的存储查询参数.我想知道是否可以在任何路由解析之前分配此参数,以帮助避免额外的呼叫,其他组件依赖于此查询来反映UI中的其他行为和未在解析器中请求的呼叫服务.

堆叠闪电战中的现场样本,没有全部的复杂性.

enter link description here

推荐答案

您可以使用下面的代码进行导航,我选中了一个复选标记以避免无限循环,因为导航调用解析器,解析器将再次导航,依此类推,因此该判断将确保当所有查询参数都存在时,导航停止.我希望它能解决你的问题

import { inject } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { of } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { CodeService } from '../services/code.service';

export const queryParamsResolver = (
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
) => {
  const router = inject(Router);
  const productId = route.paramMap.get('id');
  const status = route.queryParamMap.get('status');
  const code = route.queryParamMap.get('code');

  if (!productId) {
    return of(undefined);
  }

  // is possible navigate from here instead of send the data the component
  return inject(CodeService)
    .getQueryParamerts(+productId)
    .pipe(
      switchMap((query: any) => {
        if (!status || !code) {
          return router.navigate([state.url], {
            queryParams: query,
            queryParamsHandling: 'merge',
          });
        }
        return of(true);
      })
    );
};

stackblitz

Angular相关问答推荐

iOS Mobile Safari - HTML5视频覆盖一切

Angular 17自定义指令渲染不起作用'

Angular 17@在大小写时切换多个值

Angular 客户端应用程序无法从停靠容器解析后端服务的地址

如何将表单作为Angular 分量输入传递?

如何在 Angular 中每 x 秒从 REST api 加载数据并更新 UI 而不会闪烁?

Angular Mat Select 显示键盘焦点和鼠标悬停焦点的问题

使用Dragula时,ReactiveForm元素在拖动副本中显示不同的