简体   繁体   中英

Angular2 Router navigate with multiple params issue

I'm trying to get the Angular2 new router working and I got most of it so far, except one annoying issue I can't solve.

For some reason when I use the router's navigate function with 2 parameters (matrix params) it will not run the subscribe code if one of the params is already populated and not changed, even if the other param changes.

Example:

import {ActivatedRoute, Router} from '@angular/router';
@Component({.... })

export class AnalystSearch implements OnInit, OnDestroy {
    querySubscriber: any;
    filterString:string;
    constructor(private route:ActivatedRoute, private router:Router) {
    }

    ngOnInit() {
        this.querySubscriber = this.route.params.subscribe(params => {
            //Do Things
        });
    }

    ngOnDestroy() {
        this.querySubscriber.unsubscribe();
    }

    filter():void {

        let params:any = this.route.snapshot.params;
        params["filter"] = encodeURIComponent(this.filterString);
        params["search"] = params["search"] || "";

        this.router.navigate(["/analysts", {search: params.search, filter: params.filter}]);
    }
}

Usually when filter() is called params already contains a search value (meaning - {search: "someRandomString"} and the change is that I add/modify the filter attribute (so it looks like - {search: "someRandomString", filter: "someFilterString"} )

I can see the url changing accordingly, but the code in the params.subscribe isn't running!! Why??

Note that if I change the value in the param.search attribute it will fire the code in params.subscribe .

Thanks for your help!

In this comment on a similar issue, it is suggested that you target the parent router to get the params.

In your case, something like

this.router.routerState.parent(this.route).params.subscribe(params => {...})

should do the trick.

I have no idea why it has to be so ugly. I expected this to work the way you did it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM