How to disable url changes with Angular routing

扶醉桌前 提交于 2020-02-22 10:57:15

问题


My Angular 7 app needs to be rendered in an iFrame. Due to the peculiar nature of the system, I need to prevent the URL from changing, or maybe I should say that I need Angular not to expect the URL to change.

I've found posts that show how to prevent it on specific routing calls, but the URL is updated when the app loads too.

The objective is to maintain the URL like: website.com/applicaition, even when the route changes such that there is no update to the window.location.

https://website.com/application [desired for every view] https://website.com/application/home [NOT desired for ANY view]

Thanks, Wayne


回答1:


If you don't wish to have the URL updated, at all, you need to do two things.

First, add:

{ initialNavigation: false }

to the router settings like this:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '**', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { initialNavigation: false })],
  exports: [RouterModule]
})

Unfortunately, I couldn't find a way to update this globally, so you will need to set the following for each navigation point in the app.

With router-links:

<a routerLink="/home" routerLinkActive="active" skipLocationChange="true" >Home</a>

With ts navigation calls:

router.navigate(['/home', { skipLocationChange: true }];

I hope this helps!




回答2:


A better approach would be to implement a route guard at the root route (or a wildcard) that just always returns false.

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: '**',
        canActivate: [NeverActivate]
      }
    ])
  ],
  providers: [NeverActivate, UserToken, Permissions]
})


@Injectable()
class NeverActivate implements CanActivate {

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return false; // never allow activation
  }
}


来源:https://stackoverflow.com/questions/53196790/how-to-disable-url-changes-with-angular-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!