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

类似的

this._router.navigate(LASTPAGE);

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

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

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


当前回答

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

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

其他回答

我这样做的方式,而导航到不同的页面添加一个查询参数通过传递当前位置

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

这应该能够导航到前一页。而不是使用位置。我觉得上面的方法是更安全的考虑情况下,用户直接登陆到你的页面,如果他按后退按钮的位置。回到它将重定向用户到前一页,这将不是你的网页。

我是这么说的:

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

用Angular 5.2.9测试过

如果你使用锚而不是按钮,你必须使用href="javascript:void(0)"将其设置为被动链接,以使Angular Location正常工作。

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  constructor( private location: Location ) { 
  }

  goBack() {
    // window.history.back();
    this.location.back();

    console.log( 'goBack()...' );
  }
}

app.component.html

<!-- anchor must be a passive link -->
<a href="javascript:void(0)" (click)="goBack()">
  <-Back
</a>

实际上,你可以利用内置的位置服务,它拥有一个“返回”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};线条很重要。

另一个解决方案

window.history.back ();