【问题标题】:Get Previous URL in Angular在 Angular 中获取上一个 URL
【发布时间】:2020-08-18 15:14:12
【问题描述】:

我需要 Angular TS 文件的 OnInit 函数中的 Previous URL。

ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }

我可以通过上面的代码,但这会重复多次,因为我在 Parent 下有很多子组件。 我需要任何其他方法,它只运行一次

【问题讨论】:

  • 保存在 sessionStorage 或 localStorage 中
  • @ShlokNangia 重复多次
  • @ShlokNangia 如果我访问了任何其他组件,此代码也会重复!!!!

标签: angular url router


【解决方案1】:

您可以尝试使用基于此article的解决方案

@Injectable({
  providedIn: 'root'
})
export class RoutingStateService
{
  private history = [];

  constructor(private router: Router, @Inject(DOCUMENT) private _document: any)
  {
  }

  public recordHistory(): void
  {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(({urlAfterRedirects}: NavigationEnd) => {
        this.history = [...this.history, urlAfterRedirects];
      });
  }

  public getHistory(): string[]
  {
    return this.history;
  }

  public getPreviousUrl(): string
  {
    return this.history[this.history.length - 2] || this._document.referrer;
  }
}

然后在你的主组件的构造函数中,注入这个服务并调用recordHistory

【讨论】:

  • 它不适合我!!
  • 我澄清了一点我的答案。如果这仍然不起作用,您能否详细说明您的问题是什么?有什么错误吗?你在代码中设置断点了吗?
  • 我有父组件和多个子组件。我需要从 Child 到 Parent 的先前 url,并且此 url 代码不得影响任何其他组件。如果我添加了代码(鉴于我的问题),那将重复多次。通过在我的父组件中添加您的代码,我没有得到任何 URL。它总是给未定义的
  • 父组件的oninit函数中需要之前的URL
【解决方案2】:

https://community.wia.io/d/22-access-the-previous-route-in-your-angular-5-app

这很好用。更好地使用服务,服务只会在需要时执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2019-08-29
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多