获取 Angular 中的上一个 URL

Get Previous URL in Angular

我需要 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 下有很多子组件。 我需要任何其他方法,它只运行一次

您可以尝试使用基于此的解决方案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

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

这个效果很好。更好地使用服务,服务将仅在需要时执行。