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

类似的

this._router.navigate(LASTPAGE);

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

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

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


当前回答

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

其他回答

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

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

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

在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

<按钮返回按钮>返回</button>

你可以把它放到一个指令中,这个指令可以附加到任何可点击的元素上:

import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';

@Directive({
    selector: '[backButton]'
})
export class BackButtonDirective {
    constructor(private location: Location) { }

    @HostListener('click')
    onClick() {
        this.location.back();
    }
}

用法:

<button backButton>BACK</button>

我是这么说的:

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