Sum*_*ant 6 angular2-routing angular
想要将 SkipLocationChange 设置为 true 作为我的 Angular2 应用程序的默认值。如何?例如,一个应用程序可能有多个调用router.navigate
this.router.navigate(['/path', arg], {skipLocationChange:true})
Run Code Online (Sandbox Code Playgroud)
也许有 50 次调用 router.navigate,这需要样板化这个选项skipLocationChange:true50 次……
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;
}
}
Run Code Online (Sandbox Code Playgroud)
并将其链接到配置中的每个路由,例如:
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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
939 次 |
| 最近记录: |