Angular:导航后获取原点

Angular: Get origin after navigation

晚安,

我有以下(简单的)问题。我有 2 个组件导航到一个组件中的 1 个组件,我想知道导航来自哪个组件,以便我可以采取相应的行动(在这种情况下是否刷新列表)。问题是 url 在两个组件中是相同的。

// Component: ToolbarComponent
// URL: /products/123
navigateBack() {
  this.router.navigate(['/products']);    
}

-

// Component: ProductDetailComponent
// URL: /products/123
navigateBack() {
  this.router.navigate(['/products']);    
}

-

// Component: ProductsComponent
// URL: /products
public constructor() {
  this.navigationSubscription = this.router.events.subscribe((e: any) => {
        if (e instanceof NavigationEnd && 
            e.urlAfterRedirects.endsWith('products')) {
            // Here i want to know the origin, ToolbarComponent or ProductDetailComponent
        }
}

我认为上面的简化代码很好地说明了我想要完成的任务。

提前致谢!

编辑:我不希望原点在 url 中可见。

您可以使用查询参数或服务来处理 class 将跟踪用户来自哪里?

this._router.navigate(['/products'], { queryParams: { from:'viewname' } });

正如@Suresh 提供的那样,您可以使用 queryParams。这个解决方案的问题是它会用不必要的参数污染 URL 。

您可以改为使用共享服务,您将在其中存储来电者:

export class SharingService {
  ...
  navigateBack(caller: any) {
    this.caller = caller;
    this.router.navigate(['/products']);    
  }
}

在您的组件中:

navigateBack() {
  this.sharingService.navigateBack(this);    
}

您现在可以在之前的组件中测试调用者是否是任一组件的实例:

ngOnInit() {
  if (this.sharingService.caller instanceof ComponentOne) { ... }
  else if (this.sharingService.caller instanceof ComponentTwo) { ... }
}