如何返回上一页

581

在Angular 2中,有没有一种聪明的方法返回上一页?

类似于

this._router.navigate(LASTPAGE);
例如,页面C有一个返回按钮,
  • 从页面A跳转到页面C,点击按钮,返回页面A。

  • 从页面B跳转到页面C,点击按钮,返回页面B。

路由器是否具有此历史信息?
29个回答

11
我在导航到不同的页面时,通过传递当前位置添加一个查询参数的方式进行操作。
this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }

在您的组件中读取此查询参数

this.router.queryParams.subscribe((params) => {
    this.returnUrl = params.returnUrl;
});
如果returnUrl存在,则启用“后退”按钮,当用户点击“后退”按钮时。
this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa

这应该能够导航到上一页。我认为使用上述方法比使用location.back更安全,考虑到用户直接着陆在您的页面上并且如果他使用location.back按下返回按钮,它将重定向用户到以前的页面,这将不是您的网页。


需要导入ActivatedRoute并在queryParams订阅中使用它(例如,this.route.queryParams.subscribe),但除此之外,似乎可以工作! - Stephen Kaiser
对我来说,即使在 Angular 4 中,使用路由器本身也能正常工作。 - Puneeth Rai
1
最佳答案是,在Angular 5(直到x?)中,您需要注入“ActivatedRoute”对象,并在此对象上使用queryParams,就像Stephen Kaiser已经说明的那样。 - Satria

6
在RC4中:
import {Location} from '@angular/common';

7
这是对答案的补充,而不是答案本身。 - Vega

4

另一种解决方案:

window.history.back();


对我来说,location.back() 可以工作,但是当我使用 --prod 编译时就不行了。 - Alex

4
请确保在使用最新的Angular/TypeScript时进行显式导入。
import { Location } from '@angular/common';

 onCancel() {
    this.location.back();
  }

1
很不幸,答案早在5年前就已经给出了,甚至还错过了在构造函数中定义“location”的部分。 - bvdb
是的,在你的 constructor() 中不要忘记定义: private location: Location - Dylan Moguilevsky
如上所述,对于其中一种提出的解决方案,请注意存在一个边缘情况,即如果用户打开一个新标签页,则历史记录中将没有条目可供返回。这可能会使用户退出Angular应用程序,并引入安全问题,因为没有直接检查浏览器历史记录的API。 - Ali Celebi

3
自beta 18版本以来: import {Location} from 'angular2/platform/common';

3

2022
利用您的应用程序路由 - 更像是“Angular方法”,而不是访问浏览器的位置对象来查看导航历史记录。考虑为什么需要用户返回,并且在应用程序及其路由的更广泛上下文中,“返回”意味着什么。

例如,从子路由返回到父路由。

  this.router.navigate(['..'], {relativeTo: this.route});

您还可以阅读有关上一个导航的内容。

previousNavigation:先前成功的导航对象。只有一个上一个导航可用,因此此先前的导航对象对其自身的previousNavigation具有空值。


4
这似乎会带您沿着路径前进,而不是返回到先前的位置。 - Olix

3
若不想刷新页面就想返回上一页,我们可以在html中使用以下代码:javascript:history.back()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>

1
我建议使用Location服务。官方API - hastrb

2

我想到了这个,你也可以检查是否有上一页。 确保在你的appComponent中使用该服务。

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

interface HistoryData {
  previousPage: string | null,
  currentPage: string | null,
}

@Injectable({ providedIn: 'root' })
export class GoBackService {

  private historyData: HistoryData = { previousPage: null, currentPage: null };

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

  public goBack(): void {
    if (this.historyData.previousPage) this.location.back();
  }

  public canGoBack(): boolean {
    return Boolean(this.historyData.previousPage);
  }

}

2

导入:

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

构造函数:

constructor(private readonly router: Router, private readonly location: Location) {
  location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}

可选项,避免在应用程序外部返回:

private canGoBack: boolean = false;

constructor(private router:Router,private location:Location){
  this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}

返回:

goBack(): void {
  if (this.canGoBack) {
    this.location.back();
  }
}

HTML:

<button (click)="goBack()"></button>

2

我正在使用这种方式:

import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'

@Component({
    selector: 'Back_page',
    template: `<button  (click)="onBack()">Back</button>`,
})
export class BackPageComponent {
  constructor(private location: Location) { }

  onBack() {
    this.location.back();// <-- go back to previous location
  }
}

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