关于前端:关于-Angular-应用对浏览器-Back-按钮支持问题的讨论

6次阅读

共计 1586 个字符,预计需要花费 4 分钟才能阅读完成。

需要 1:如果开发人员想禁用整个应用程序或多个组件的后退按钮
需要 2:如果只想禁用特定组件的后退按钮

对于第一个要求,一个可行的方法是,实现一个 Guard 并将其利用于所需的路由。

示例代码:

import {LocationStrategy} from '@angular/common';

@Component({selector: 'app-root'})
export class AppComponent {
  constructor(private location: LocationStrategy) {history.pushState(null, null, window.location.href);
    // check if back or forward button is pressed.
    this.location.onPopState(() => {history.pushState(null, null, window.location.href);
        this.stepper.previous();});
  }
}

Spartacus 我的项目里 RoutingService 的 back 办法实现。Visual Studio Code 的 peek reference 性能显示,没有其余代码调用了这个 back 办法。

Angular 中的 CanDeactivate Guard 可用于防止导航到 与应用程序雷同域的另一个页面

当咱们在浏览器地址栏输出一个新的 URL 地址时,咱们失去一个新页面,这个 URL 保留在浏览器历史记录中。应用这个历史记录,咱们能够回退到以前浏览过的页面。

像 Angular 这样的 SPA 应用程序呢?大多数状况下,在 Angular 中咱们有一个动态路由,但咱们会更改当前页面上的外部组件。

规范浏览器历史记录对 Angular 这种单页面利用不起作用。咱们能够编写本人的服务,当用户在咱们的 Angular 应用程序中更改路由时监听。新 Route 将被保留,当用户点击后退按钮时,咱们给出最初保留的路由记录。

在咱们存储路线历史的导航服务中,咱们订阅了 Route 更改事件。咱们将每条新路线保留在一个数组中。显然,这个服务蕴含了一个获取之前路由并返回的办法。

Spartacus 针对这个 navigationEnd 事件并没有非凡的解决:

看个具体的例子。

UserListComponent 应该蕴含所有用户的列表,而 ActiveUsersComponent 只蕴含局部用户。这两个组件都将链接到 UserDetailComponent,而后咱们心愿从该组件导航回来。

const routes: Routes = [
  {
    path: 'users',
    component: UsersComponent,
    children: [{ path: '', component: UserListComponent},
      {path: 'active', component: ActiveUsersComponent},
      {path: ':id', component: UserDetailComponent},
    ],
  },
  {path: '**', redirectTo: 'users'},
]

动态路由

一种解决方案是在详细信息组件中定义路由器链接,并应用相对路由显式导航回父级:

<a routerLink="/users">Back with Absolute Routing</a>

或者,也能够从组件类以编程形式执行此操作,但请记住,router links 比通过点击事件触发的导航从语义上来说更清晰。

import {Router} from '@angular/router'

@Component({...})
export class UserDetailComponent {constructor(private router: Router) {}

  back(): void {this.router.navigate('/users')
  }
}
正文完
 0