本文共 1835 字,大约阅读时间需要 6 分钟。
本文翻译自:
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? 路由器是否有此历史记录信息?
参考:
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);
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(); }}
自Beta 18开始:
import {Location} from 'angular2/platform/common';
在RC4中:
import {Location} from '@angular/common';
In the final version of Angular 2.x / 4.x - here's the docs 在Angular 2.x / 4.x的最终版本中-这是文档
/* 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 }}
转载地址:http://iwjnb.baihongyu.com/