代码之家  ›  专栏  ›  技术社区  ›  Tabares

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

  •  1
  • Tabares  · 技术社区  · 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中的其他行为,并调用解析器中不需要的服务。

    堆叠的现场样品,没有整个复杂性。

    enter link description here

    1 回复  |  直到 1 年前
        1
  •  1
  •   Naren Murali    1 年前

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

    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

    推荐文章