我希望将SkipLocationChange设置为我的Angular2应用程序的默认值。如何实现?例如,一个应用程序可能有多个对router.navigate
的调用。
this.router.navigate(['/path', arg], {skipLocationChange:true})
或许需要调用50次router.navigate,每次都需要复制粘贴这个选项skipLocationChange:true
50遍......
我希望将SkipLocationChange设置为我的Angular2应用程序的默认值。如何实现?例如,一个应用程序可能有多个对router.navigate
的调用。
this.router.navigate(['/path', arg], {skipLocationChange:true})
或许需要调用50次router.navigate,每次都需要复制粘贴这个选项skipLocationChange:true
50遍......
您可以通过创建一个守卫来实现这一点,该守卫通过重新运行导航来“修改”extras
:
@Injectable({
providedIn: 'root',
})
export class SkipLocationChangeGuard implements CanActivate {
constructor(private readonly router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// If skipLocationChange is true, allow to proceed
const extras = this.router.getCurrentNavigation()?.extras;
if (extras?.skipLocationChange) {
return true;
}
// Otherwise, rerun the navigation with skipLocationChange on
const url = this.router.parseUrl(state.url);
this.router.navigateByUrl(url, {...extras, skipLocationChange: true});
return false;
}
}
const routes: Routes = [
{path: 'foo', component: FooComponent},
{path: 'bar', component: BarComponent},
{path: '', pathMatch: 'full', redirectTo: '/foo'},
];
/** Adds a guard to every non-redirect route. */
const addLocationGuard = (r: Route): Route => r.redirectTo ? r : {...r, canActivate: [SkipLocationChangeGuard]};
@NgModule({
imports: [
RouterModule.forRoot(routes.map(addLocationGuard)),
],
exports: [RouterModule],
declarations: [],
})
export class AppRoutingModule {}