Angular2 + 如何将SkipLocationChange设置为默认值为true

6

我希望将SkipLocationChange设置为我的Angular2应用程序的默认值。如何实现?例如,一个应用程序可能有多个对router.navigate的调用。

this.router.navigate(['/path', arg], {skipLocationChange:true})

或许需要调用50次router.navigate,每次都需要复制粘贴这个选项skipLocationChange:true 50遍......


你最近有没有解决这个问题? - Adam Hughes
1个回答

0

您可以通过创建一个守卫来实现这一点,该守卫通过重新运行导航来“修改”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 {}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接