在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页。
路由器有这个历史信息吗?
当前回答
<按钮返回按钮>返回</button>
你可以把它放到一个指令中,这个指令可以附加到任何可点击的元素上:
import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
constructor(private location: Location) { }
@HostListener('click')
onClick() {
this.location.back();
}
}
用法:
<button backButton>BACK</button>
其他回答
你可以在你的路由类上实现routerOnActivate()方法,它会提供之前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
然后你可以使用router.navigateByUrl()并传递ComponentInstruction生成的数据。例如:
this._router.navigateByUrl(prevInstruction.urlPath);
我这样做的方式,而导航到不同的页面添加一个查询参数通过传递当前位置
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
这应该能够导航到前一页。而不是使用位置。我觉得上面的方法是更安全的考虑情况下,用户直接登陆到你的页面,如果他按后退按钮的位置。回到它将重定向用户到前一页,这将不是你的网页。
<按钮返回按钮>返回</button>
你可以把它放到一个指令中,这个指令可以附加到任何可点击的元素上:
import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
constructor(private location: Location) { }
@HostListener('click')
onClick() {
this.location.back();
}
}
用法:
<button backButton>BACK</button>
是的,你能做到。在你的typescript组件上编写这段代码,然后享受吧!
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'return_page',
template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
constructor(private location: Location) { }
onReturn() {
this.location.back();
}
}
只需使用Location,这是一个Angular服务,应用程序可以使用它与浏览器的URL进行交互。
导入:
import { Location } from '@angular/common';
注射:
constructor(private location: Location) { }
简单地使用它:
goBack() {
this.location.back(); // Navigates back in the platform's history
}