Angular 路由器和浏览器后退按钮

问题描述 投票:0回答:1

在我的 Angular 应用程序(版本 13)中,我有三个组件:A、B 和 C,每个组件分别对应于路由 Route-A、Route-B 和 Route-C。考虑一个路由场景,我通过单击按钮从路由 A 路由到路由 B。在组件 B 中,我在 ngOnInit() 中有一些逻辑,具体取决于它有时从路由 B 路由到路由 C 的逻辑。但问题是来自 C 组件,当我单击浏览器后退按钮时,它会将我带到组件 A。但我想返回到组件 B 而不是 A。我怎样才能实现这一点?

angular browser router angular-router back-button
1个回答
0
投票

浏览器存储一堆 URL。只有当 URL 更改并存储在浏览器的导航历史记录中时,您才能导航回之前的路线。 Angular 以编程方式更改路由,而不实际将 URL 存储在历史记录中。您可以在浏览器的历史记录中验证这一点。

现在,据我所知,在这种情况下,您有两种选择。

1。存储路由状态

在组件 B 中

import { Router } from '@angular/router';

constructor(private router: Router) {}

ngOnInit() {
  // Your logic to navigate to component C based on certain conditions
  if (shouldNavigateToC) {
    // Store flag in Router's navigation extras to indicate navigation from B to C
    this.router.navigate(['/route-C'], { state: { fromBToC: true } });
  }
}

在A部分

import { Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

ngOnInit() {
  // Subscribe to Router events to detect navigation start
  this.router.events.subscribe(event => {
    if (event instanceof NavigationStart) {
      // Check if navigation back is coming from component C
      const navigationExtras = this.router.getCurrentNavigation()?.extras.state;
      if (navigationExtras && navigationExtras.fromBToC) {
        // Redirect to component B instead of default behavior (component A)
        this.router.navigate(['/route-B']);
      }
    }
  });
}

通过此实现,当从组件 C 导航回来时,Angular 会将您重定向到组件 B,而不是默认行为(导航到组件 A)。这使您可以根据应用程序逻辑维护预期的导航流程。

2。导航历史解决方案

我非常喜欢这个解决方案,因为它可以扩展到全球水平。 创建一个导航历史记录服务,该服务订阅路线更改并将之前的路线存储为historyUrl(您也可以将其存储在数组中)。 这里来自角度路由器的位置服务可以访问浏览器和历史记录。

以下是基础课程,您可以扩展至更高级的课程。

import { Injectable } from '@angular/core';
import { Location, NavigationEnd, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class BackButtonService {
  private historyUrl: string | null = null;

  constructor(private location: Location, private router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.historyUrl = event.urlAfterRedirects;
      }
    });
  }

  goBack() {
    if (this.historyUrl) {
      this.location.back();
    } else {
      // Handle the case where there's no history (e.g., initial route)
      // You can stay on the current page or redirect to a specific route.
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.