在Angular中获取上一个URL

问题描述 投票:-1回答:1

我需要在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
            });
    }

我可以用上面的代码,但是这个函数重复了很多次,因为我在父组件下有很多子组件,我需要任何其他方法,只运行一次。

angular url router
1个回答
0
投票

你可以尝试使用基于这个的解决方案 文章

@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


0
投票

https:/community.wia.iod22-access-the-previous-route-in-your-angular-5-app。

这个很好用。最好使用Service,Service只在需要时才会执行。

© www.soinside.com 2019 - 2024. All rights reserved.