La guardia de ruta cambia al ampliar las rutas

Sterling Store Engagement utiliza los guardianes de ruta de Angular para controlar la navegación a ciertas rutas que se basan en condiciones. Por lo tanto, cuando se amplían las rutas, se realizan ciertos cambios en la guarda de ruta.

Por ejemplo, el protector de ruta angular ValidatePackOrderGuard que está presente en el archivo store-single-spa/packages/features/pack-order/src/app/features/pack-order/pack-order-page/validate-pack-order.guard.ts se utiliza para validar si un envío se encuentra en un estado válido antes de pasar a la página Empacar productos. Si el envío no se encuentra en estado válido, no se mostrará la página Empacar productos.

Los guardianes de ruta de Angular necesitan ser cambiados cuando extiendes cualquier ruta que esté protegida por el guardián de ruta. Por ejemplo, si extiendes el PackOrderPageComponent en el flujo del paquete, modifica el ValidatePackOrderGuard protector de ruta angular.

Para modificar el ValidatePackOrderGuard protector de ruta angular, complete los siguientes pasos:
  1. En el archivo de servicio de datos utilizado por la ruta, añade el asunto routingInProgress$. En este caso, PackOrderPageDataService es el servicio de datos.
    import { Subject } from 'rxjs';
    public routingInProgress$: Subject<boolean> = new Subject<boolean>();
  2. En la guardia de ruta, añada la variable routingInProgress como sigue:
    public routingInProgress = false;
  3. Incluye el código en el método canActivate dentro del bloque if(!this.routingInProgress).
  4. Establezca el routingInProgress) en true.
  5. En el manejador de promesas, restablece el routingInProgress a false, y emite routingInProgress$.next(false).
  6. Añada la sentencia this._location.back(); en el bloque else como se ilustra en el siguiente fragmento de código. Puede encontrar los cambios dentro de //Extension changes - start // y //Extension changes - end // comentario.
    /*******************************************************************************
    * IBM Confidential
    * IBM Sterling Order Management (5737-D18)
    * IBM Sterling Order Management Software (5725-D10)
    * (C) Copyright IBM Corp. 2022
    ******************************************************************************/
    
    import { Location } from '@angular/common';
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
    import { routePath, UIUtil } from '@store/core';
    import { PackOrderPageDataService } from './pack-order-page-data.service';
    
    @Injectable()
    export class ValidatePackOrderGuard implements CanActivate {
    
      private shipmentId = '';
      // Extension changes - start //
      public routingInProgress = false;
       // Extension changes - end //
      constructor(
        private packOrderDataService: PackOrderPageDataService,
        private router: Router,
        private _location: Location
      ) { }
    
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Promise<boolean | UrlTree> | boolean | UrlTree {
    
        this.shipmentId = next.params['ShipmentNo'];
        //Extension changes - start //
        if(!this.routingInProgress){
        this.routingInProgress = true; 
        this.packOrderDataService.routingInProgress$.next(true);
        //Extension changes - end //
        return this.packOrderDataService.validatePackReqBeforePack(this.shipmentId)
          .then(
            validationStatus => {
             let validationState = validationStatus['Shipment'] && !validationStatus['Shipment'].Error ? 'continueToPack' : validationStatus;
             //Extension changes - start //
              this.routingInProgress = false;
              this.packOrderDataService.routingInProgress$.next(false);
             //Extension changes - end //
              if (validationState === 'continueToPack') {
                return true;
              } else if (validationStatus['Shipment'] && validationStatus['Shipment'].Error && validationStatus['Shipment'].Error.ErrorDescription) {
                const navigationURL = routePath(`shipment/summary/${this.shipmentId}`, 'shell');
                const queryParams = { errorMsg: validationStatus['Shipment']?.Error?.ErrorDescription };
                if (this.router.url === '/') {
                  history.replaceState('', '', '/' + navigationURL + UIUtil.jsonToQueryString(queryParams));
                }
                return this.router.createUrlTree([navigationURL], { queryParams: queryParams });
              } else {
                if (this.router.url === '/') {
                  this._location.back();
                  return true;
                } else {
                  //Extension changes - start //
                  this._location.back();
                  //Extension changes - end //
                  return false;
                }
              }
            }
          );
        }
      }
    }
  7. Suscribirse a routingInProgress$ en el método del componente de ruta ngOnInit. Por ejemplo, dentro de PackOrderPageComponent
    this.dataService.routingInProgress$.subscribe(routingInProgress => {
     if(!routingInProgress){
      this.packAllPermission = ResourcePermissionUtil.hasPermission(this.PACKALL_RESOURCE_PERMISSION);
      this.showItemImage = RulesUtil.isRuleEnabled('WSC_SHOW_ITEM_IMAGES');
      this.shipmentKey = this.activeRoute.snapshot.params['ShipmentNo'];
      this.getInitializationDataForShipment(true);
     }
     });