当skiplocationchange为true时,在Angular 6中返回上一页

4

Angular 6中的路由

当我想要导航到特定位置时,我需要使用路由。

route.navigate(['/home'], { skipLocationChange: true });

但是当返回到先前的路由时,下面的代码并没有起到帮助作用, 是否有其他方法或者应该删除 "{ skipLocationChange: true }"?
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();
  }
}

你找到如何在Angular中隐藏URL并同时能够返回的方法了吗?我也需要这个功能。 :) - manymanymore
1
不是 @YaroslavTrofimov,我写了一个服务,可以保存我的 URL 历史记录,并根据前进和后退进行推送和弹出。 - Parshuram Kalvikatte
2个回答

5
使用 skipLocationChange 导航时不会将新状态推入历史记录。
这就是为什么使用 location.back() 无效,因为它只是将浏览器返回到历史记录中的上一个状态。尽管浏览器中的 URL 已被修改,但当前状态并未更改。
如果您希望页面的下一个状态添加到浏览器的历史记录中,则不应使用 skipLocationChange

2
有没有其他方法可以隐藏我的URL? - Parshuram Kalvikatte

1

您可以将动态数据传递给路由

在Angular版本+8中,使用状态对象添加了传递动态数据或用户定义对象的选项。状态对象存储在历史API中。

使用routerLink指令

<a [routerLink]="['antherUrl']" [state]="{ id:1 , name:'currentUrl'}">Dynamic Data</a>

使用 navigateByUrl

this.router.navigateByUrl('/antherUrl', { state: { id:1 , name:'currentUrl' } });

访问状态值 可以使用路由器的 getCurrentNavigation 方法来访问状态(仅在构造函数中有效)

 perviousUrl = this.router.getCurrentNavigation().extras.state


goBack() {
 this.router.navigate([this.previousUrl.name],{skipLocationChange: true});
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接