How to detect url change in angular 7 include para

2020-05-28 18:44发布

问题:

I need to detect url change for path param and query param in one component.

{ path: 'category/:key', component: CollectionPageComponent},

The url at the end will be e.g. category/t-shirt or category/t-shirt?page=2 I need to get all product of category base on categoryLink and have paging.

I use combineLatest

combineLatest(this.route.params, this.route.queryParams)
    .pipe(map(results => ({params: results[0].key, query: results[1]})))
    .subscribe(results => {
        console.log("run me");
        console.log(results);
    });

Everything work fine except one case that will run twice like my demo link https://angular-ev2rns-subscribe-param-and-path-param.stackblitz.io

First click on cat1 and click page1 -> fire one. Second click on cat2 -> it will fire twice

Then I found other solution

ngOnInit() {
    // I have to handle it first time
    this.categoryKey = this.activatedRoute.snapshot.params.key;
    let page = this.activatedRoute.snapshot.queryParams.page;
    // call service get data
    this.sub = this.router.events.pipe(
          filter((event) => event instanceof NavigationEnd)
            )
        .subscribe((event:NavigationEnd) => {
          console.log("run me ");
          this.categoryKey = this.activatedRoute.snapshot.params.key;
          let page = this.activatedRoute.snapshot.queryParams.page;
          console.log(this.categoryKey + "|" + page);
          // call service get data
        });
}
  ngOnDestroy() {
    this.sub.unsubscribe();
  }

I dont know there is other better solution or not. I have search before I post this. Thank you every much.

标签: angular