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

类似的

this._router.navigate(LASTPAGE);

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

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

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


当前回答

你可以在你的路由类上实现routerOnActivate()方法,它会提供之前路由的信息。

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any

然后你可以使用router.navigateByUrl()并传递ComponentInstruction生成的数据。例如:

this._router.navigateByUrl(prevInstruction.urlPath);

其他回答

检测到的未更改组件的@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();
  }
}

你可以在你的路由类上实现routerOnActivate()方法,它会提供之前路由的信息。

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any

然后你可以使用router.navigateByUrl()并传递ComponentInstruction生成的数据。例如:

this._router.navigateByUrl(prevInstruction.urlPath);

进口:

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>

也为我工作时,我需要移动回文件系统。 P.S. @angular: "^5.0.0"

<button type="button" class="btn btn-primary" routerLink="../">Back</button>