如何重定向到Angular 8中的上一页



我有一个组件,用户可以从各个页面访问该组件。当用户单击"确定"时按钮,他应该被重定向到上一个页面,即他所在的页面来到这个组件。

我偶然发现window.history.back((this.router.navigation('../'(

另外,window.history.back((之间有什么区别;和这个路由器导航('../'(

我还想了解this.location.back()window.history.back()之间的区别。

要获得最后一次成功导航并导航到它,您可以使用:

const lastNav = router.getLastSuccessfulNavigation();
const previousRoute = lastNav.previousNavigation; 
router.navigateByUrl(previousRoute);

注意:由于previousRoute属于UrlTree类型,您可以直接使用它来使用navigateByUrl方法进行导航。。

关于历史.back(来自文档(:

history.back((方法使浏览器在会话历史中向后移动一页。它与调用history.go(-1(具有相同的效果。如果没有上一页,则此方法调用不执行

this.router.navigate( '../' )将使用:<a [routerLink]="['../', 'foo', 'bar']">Go Up</a>引导您在导航中达到更高的级别

所以不同的是window.history.back();会带你回来,this.router.navigate( '../' )会带你上去。。

关于您的最后一个问题:

window对象指的是当前帧,该帧具有历史对象属性,该属性返回窗口的历史对象->更多信息:https://www.w3schools.com/jsref/obj_history.asp

location应该从@angular/common导入,并在类似的构造函数中使用

import {Location} from '@angular/common';
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private location: Location) 
{}
goBack() {
this.location.back();
}
}

goBack()函数随后可由返回按钮上的onClick调用。。

看看https://angular.io/guide/architecture-components了解更多详细信息。。

尝试使用Location对象

import {Location} from '@angular/common'; 
constructor(private location: Location){}

当你需要时使用它

this.location.back();

最新更新