zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

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

2023-02-25 18:17:22 时间

需求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')
  }
}