本文翻译自:How to go back last page
Is there a smart way to go back last page in Angular 2? 有没有一种聪明的方法可以返回Angular 2的最后一页?
Something like 就像是
this._router.navigate(LASTPAGE);
For example, page C has a Go Back button, 例如,页面C具有“返回”按钮,
Page A -> Page C, click it, back to page A. 页面A->页面C,单击它,回到页面A。
Page B -> Page C, click it, back to page B. 页面B->页面C,单击它,返回页面B。
Does router have this history information? 路由器是否有此历史记录信息?
#1楼
参考:https://stackoom.com/question/2OjN5/如何返回上一页
#2楼
You can implement routerOnActivate()
method on your route class, it will provide information about previous route. 您可以在路由类上实现routerOnActivate()
方法,它将提供有关先前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
Then you can use router.navigateByUrl()
and pass data generated from ComponentInstruction
. 然后,您可以使用router.navigateByUrl()
并传递从ComponentInstruction
生成的数据。 For example: 例如:
this._router.navigateByUrl(prevInstruction.urlPath);
#3楼
Actually you can take advantage of the built-in Location service, which owns a "Back" API. 实际上,您可以利用内置的位置服务,该服务拥有“后退” API。
Here (in TypeScript): 此处(在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();
}
}
#4楼
自Beta 18开始:
import {Location} from 'angular2/platform/common';
#5楼
在RC4中:
import {Location} from '@angular/common';
#6楼
In the final version of Angular 2.x / 4.x - here's the docs https://angular.io/api/common/Location 在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
}
}