在Angular 2中有没有聪明的方法返回到最后一页?

类似的

this._router.navigate(LASTPAGE);

例如,C页有一个“返回”按钮,

A页-> C页,点击返回A页。 B页-> C页,点击它,回到B页。

路由器有这个历史信息吗?


当前回答

在angular 4中使用preserveQueryParams,例如:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

当点击链接时,您将被重定向编辑/10?Page =1,保留参数

裁判:https://angular.io/docs/ts/latest/guide/router.html # !# link-parameters-array

其他回答

检测到的未更改组件的@Parziphal答案版本:

  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);
  }

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

是的,你能做到。在你的typescript组件上编写这段代码,然后享受吧!

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

@Component({
    selector: 'return_page',
    template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
  constructor(private location: Location) { }

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

从beta 18开始:

import {Location} from 'angular /platform/common';

2022 利用你的应用程序路由-更多的是一种“角度方法”,而不是访问浏览器的位置对象来获取导航历史。 想想你为什么需要用户返回,以及“返回”在应用程序及其路由的更广泛的上下文中意味着什么。

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

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

您还可以阅读以前的导航

previousNavigation:先前成功的导航对象。只有 一个先前的导航是可用的,因此这个先前的 Navigation对象的previousNavigation为空值。

在Angular 2的最终版本中。X / 4。x -这里是文档https://angular.io/api/common/Location

/* typescript */

import { Location } from '@angular/common';
// import stuff here

@Component({
// declare component here
})
export class MyComponent {

  // inject location into component constructor
  constructor(private location: Location) { }

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