在 Angular 中:如何检查发送 Id 的先前路由,然后应用 if else 条件

问题描述

所以我想做的是。我在 angular2+ 应用程序中有三个组件

1 个带有 (/home) 路由的家

2 个带有 (/product) 路由的产品

3 个带有 (/view product) 路由的 ViewProducts。

HomeComponent 有特色产品。

ProductComponent 只有产品。

它们都有一个方法,可以将它们路由到带有特性/产品 _id 的 viewProduct 组件。

现在 ViewCompnenet 应该检查 _id 来自哪个组件,通过检查前一个 路线,然后根据路线做一些动作。

这是我的片段。

   for example
   in FeatureProductComponent / ProductComponet both have this method
   
      SendProductId(_ProductId){
        this._MessengerService.SendFeatureProductId(_ProductId);//I am using rxjs to send data to viewComponent
        this._Router.navigate(['viewProduct']);
      }
 

     Now at ViewProduct Component.ts
     ngOnInit(): void {
       if(_Id is coming from /home (route or slug){

        //run some block of code here

       }else if(_id is coming from /product (route or slug)){

       
                     ///run some block of code here

          }
     }

解决方法

我已经使用下面给出的逻辑实现并解决了这个问题。并且它工作正常只是想知道它是否是解决这个特定问题的好方法。

  viewProductComponent.ts
 
 Here docs are coming from the home/product component and it is an object
 {id:someId,Component:someComponent} and on this object i am checking form which
  component the data is coming.

     
 this._MessengerService.GetMessageWithData().subscribe((docs: any) => {
   
   if (docs.Component === "FeatureProductComponent") {
         console.log('Data Coming From Feature Product Component');
       } else if (docs.Component === "ProductComponent") {
         console.log('Data Coming From Feature Product Component');
       }
     });

  }
,

这里有你想要的 StackBlitz:

https://stackblitz.com/edit/angular-ivy-xceqqt?embed=1&file=src/index.html

  • home.component.html 和 list.component.html 中,我在 a 元素上指定了查询参数,这些参数将在导航时附加到 show.component。>

    <a ... [routerLink]='["/product",i]' [queryParams]="{from: 'home'}"><!-- or 'list' -->
        Go to product {{ i }}
    </a>
    
  • show.component.ts 中,我正在读取查询参数的值

    constructor(private route: ActivatedRoute) {
      this.route.queryParams.subscribe((params) => {
        this.from = <string>params.from;
      });
    }
    
  • 您可以在此处放置 if 子句来决定需要采取哪些操作。