在 Angular 中获取上一个 URL [英] Get Previous URL in Angular

查看:56
本文介绍了在 Angular 中获取上一个 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 Angular TS 文件的 OnInit 函数中的上一个 URL.

I need Previous URL in OnInit function of Angular TS file.

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

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

I can get by above Code, but this Repeats multiple times, because I am having lot of child component under Parent. I need any other method, which runs only onces

推荐答案

您可以尝试使用基于此文章

@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

Then in your main component's constructor, inject this service and call recordHistory

这篇关于在 Angular 中获取上一个 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆