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

类似的

this._router.navigate(LASTPAGE);

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

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

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


当前回答

<按钮返回按钮>返回</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-button',
    template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
    @Input()color: string;

  constructor(private location: Location) { }

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

然后在需要后退按钮时将其添加到任何模板中。

<back-button color="primary"></back-button>

注意:这里使用的是Angular材质,如果你不使用这个库,那么移除垫子按钮和颜色。

进口:

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>

从beta 18开始:

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

实际上,你可以利用内置的位置服务,它拥有一个“返回”API。

这里(TypeScript中):

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

@Component({
  // component's declarations here
})
class SomeComponent {

  constructor(private _location: Location) 
  {}

  backClicked() {
    this._location.back();
  }
}

编辑:正如@charith所提到的。Location应该从@angular/common中导入,所以从@angular/common中导入{Location};线条很重要。

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