在Angular 2中有没有聪明的方法返回到最后一页?
类似的
this._router.navigate(LASTPAGE);
例如,C页有一个“返回”按钮,
A页-> C页,点击返回A页。 B页-> C页,点击它,回到B页。
路由器有这个历史信息吗?
在Angular 2中有没有聪明的方法返回到最后一页?
类似的
this._router.navigate(LASTPAGE);
例如,C页有一个“返回”按钮,
A页-> C页,点击返回A页。 B页-> C页,点击它,回到B页。
路由器有这个历史信息吗?
当前回答
在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
其他回答
你可以在你的路由类上实现routerOnActivate()方法,它会提供之前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
然后你可以使用router.navigateByUrl()并传递ComponentInstruction生成的数据。例如:
this._router.navigateByUrl(prevInstruction.urlPath);
从beta 18开始:
import {Location} from 'angular /platform/common';
只需使用Location,这是一个Angular服务,应用程序可以使用它与浏览器的URL进行交互。
导入:
import { Location } from '@angular/common';
注射:
constructor(private location: Location) { }
简单地使用它:
goBack() {
this.location.back(); // Navigates back in the platform's history
}
用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>
我这样做的方式,而导航到不同的页面添加一个查询参数通过传递当前位置
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
这应该能够导航到前一页。而不是使用位置。我觉得上面的方法是更安全的考虑情况下,用户直接登陆到你的页面,如果他按后退按钮的位置。回到它将重定向用户到前一页,这将不是你的网页。