Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How do I get params of a route from outside of a router-outlet

Similar question to Angular2 Get router params outside of router-outlet but targeting the release version of Angular 2 (so version 3.0.0 of the router). I have an app with a list of contacts and a router outlet to either display or edit the selected contact. I want to make sure the proper contact is selected at any point (including on page load), so I would like to be able to read the "id" param from the route whenever the route is changed.

I can get my hands on routing events by subscribing to the router's events property, but the Event object just gives me access to the raw url, not a parsed version of it. I can parse that using the router's parseUrl method, but the format of this isn't particularly helpful and would be rather brittle, so I'd rather not use it. I've also looked all though the router's routerState property in the routing events, but params is always an empty object in the snapshot.

Is there an actual straight forward way to do this that I've just missed? Would I have to wrap the contact list in a router-outlet that never changes to get this to work, or something like that?

like image 238
Ixonal Avatar asked Oct 03 '16 16:10

Ixonal


Video Answer


1 Answers

If any body was looking for the latest solution of this issue (angular 8) I stumbled upon this article which worked very well for me.

https://medium.com/@eng.ohadb/how-to-get-route-path-parameters-in-an-angular-service-1965afe1470e

Obviously you can do the same implementation straight in a component outside the router outlet and it should still work.

    export class MyParamsAwareService {
  constructor(private router: Router) { 
    this.router.events
      .pipe(
        filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
        map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
      )
      .subscribe(params => {
      console.log(params);
      // Do whatever you want here!!!!
      });
  }

In the hope to spare the same struggle I went through.

like image 148
Mark Odey Avatar answered Sep 25 '22 13:09

Mark Odey