在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页。
路由器有这个历史信息吗?
当前回答
也为我工作时,我需要移动回文件系统。 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
这应该能够导航到前一页。而不是使用位置。我觉得上面的方法是更安全的考虑情况下,用户直接登陆到你的页面,如果他按后退按钮的位置。回到它将重定向用户到前一页,这将不是你的网页。
如果你使用的是最新的Angular/TypeScript,请确保你显式导入
import { Location } from '@angular/common';
and
onCancel() {
this.location.back();
}
我做了一个按钮,我可以在我的应用程序的任何地方重复使用。
创建这个组件
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材质,如果你不使用这个库,那么移除垫子按钮和颜色。
从beta 18开始:
import {Location} from 'angular /platform/common';
用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>