如何使用解析器处理角度路由中存储的查询参数以避免任何额外的导航?

问题描述 投票:0回答:1

我有这样的场景:我将查询参数保存在服务中,以便在用户关闭浏览器时保持此数据的活动状态,使用解析器我使用活动路由的结果在 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 中的其他行为并调用解析器中不需要的服务。

stackblitz 中的实时示例,没有全部复杂性。

在此输入链接描述

angular routes router angular-resolver navigateurl
1个回答
0
投票

您可以使用下面的代码进行导航,我已经进行了检查以避免无限循环,因为导航会调用解析器,解析器会再次导航等等,因此此检查将确保当所有查询参数都存在时导航停止。希望能解决您的问题

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);
      })
    );
};

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.