在Angular中:如何检查发送Id的上一个路由,然后应用if-else条件



所以我想做的是。我在angular2+Application 中有三个组件

1带(/Home(路线的Home

2具有(/产品(路线的产品

3 ViewProducts与(/view product(路线。

HomeComponent有功能产品。

ProductComponent只有产品。

它们都有一个方法,可以将它们路由到带有feature/product_id的viewProductComponent。

现在ViewCompnet应该通过检查前面的路线,然后根据路线做一些动作。

这是我的片段。

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子句来决定需要采取的操作。

相关内容

最新更新