在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页。
路由器有这个历史信息吗?
当前回答
要返回而不刷新页面,我们可以像下面这样在html中做 javascript: history.back ()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
其他回答
检测到的未更改组件的@Parziphal答案版本:
import { Location } from '@angular/common';
import { Router } from '@angular/router';
constructor(private readonly router: Router, private readonly location: Location) {
location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}
goBack(): void {
if (this.canGoBack) {
this.location.back();
}
}
进口:
import { Location } from '@angular/common';
import { Router } from '@angular/router';
构造函数:
constructor(private readonly router: Router, private readonly location: Location) {
location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}
可选,避免返回到应用程序之外:
private canGoBack: boolean = false;
constructor(private router:Router,private location:Location){
this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}
返回:
goBack(): void {
if (this.canGoBack) {
this.location.back();
}
}
Html:
<button (click)="goBack()"></button>
实际上,你可以利用内置的位置服务,它拥有一个“返回”API。
这里(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();
}
}
编辑:正如@charith所提到的。Location应该从@angular/common中导入,所以从@angular/common中导入{Location};线条很重要。
试试routerLink = " - LASTPAGE”
2022 利用你的应用程序路由-更多的是一种“角度方法”,而不是访问浏览器的位置对象来获取导航历史。 想想你为什么需要用户返回,以及“返回”在应用程序及其路由的更广泛的上下文中意味着什么。
例如,从子路由返回到父路由
this.router.navigate(['..'], {relativeTo: this.route});
您还可以阅读以前的导航
previousNavigation:先前成功的导航对象。只有 一个先前的导航是可用的,因此这个先前的 Navigation对象的previousNavigation为空值。