简体   繁体   中英

Angular CanDeactivate is not triggered when there are query parameters in the route

I have two child modules, I need to display a confirmation on browser refresh on the product route. I have added canDeactivate and using at product module level. canDeactivate triggers fine when I do refresh on the route like http://example.com/product , but is not triggered where there a query parameter in the route like http://example.com/product?id=1 Can you please help figuring out the issue?

export const APP_ROUTES: Routes = [
    { path: '', redirectTo: 'main', pathMatch: 'full' },
    {
        path: 'main',
        loadChildren: () => import('./main/main.module').then(m => m.MainModule),
        pathMatch: 'full',
    },
    {
        path: 'product',
        loadChildren: () => import('./product/product-creation.module').then(m => m.ProductCreationModule),
        canActivate: [AuthGuard]
    }

];

product module route

export const PRODUCT_ROUTES: Routes = [
    {
        path: '',
        component: ProductComponent,
        canDeactivate: [ProductConfirmGuard],
        runGuardsAndResolvers: 'always'
    }
];

CanDeactivate Guard

@Injectable({
    providedIn: 'root'
})
export class ProductConfirmGuard implements CanDeactivate<ProductComponent> {
    canDeactivate(
        component: ProductComponent,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState?: RouterStateSnapshot
    ): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
         if (!component.canDeactivate()) {
          return confirm('Are you sure you want to discard your changes?');
        }
        return true;
    }
}

I am not 100% sure on this, but wildcard ** route should solve this. If not look for other options but the problem is, that quard ProductConfirmGuard is only activating on parent route '' because you've said so on PRODUCT_ROUTES .

export const PRODUCT_ROUTES: Routes = [
    {
        path: '**',
        component: ProductComponent,
        canDeactivate: [ProductConfirmGuard],
        runGuardsAndResolvers: 'always'
    }
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM