1

I have a split screen design. I'd like to access the folder ID from the parent route only when the child route is activated. The below works in getting the correct params for me, but on the initial load where I'm only displaying the parent route, I get a console error:

Cannot read property 'params' of null

this.activatedRoute.firstChild.params.subscribe((urlParameters) => {
  this.folder_id = urlParameters['folderId'];
});

Is there a way to only activate the above once the child has been activated?

Que
  • 957
  • 2
  • 14
  • 35
  • does this work? if(this.activatedRoute.firstChild) this.activatedRoute.firstChild.params.subscribe((urlParameters) => { this.folder_id = urlParameters['folderId']; }); – ABOS Dec 09 '18 at 12:04
  • haha, it does. I can't believe I didn't think of that. @ABOS, you gent. If you write it up as an answer, I'll accept it :) – Que Dec 09 '18 at 12:10
  • glad it works:) – ABOS Dec 09 '18 at 13:31

2 Answers2

2

you can simply try

 if(this.activatedRoute.firstChild) 
   this.activatedRoute.firstChild.params.subscribe((urlParameters) => { 
     this.folder_id= urlParameters['folderId']; 
   });
ABOS
  • 3,723
  • 3
  • 17
  • 23
0

You can subscribe to routeParams change, but trigger only when child exists and has what you need. ABOSes version won't work, because it won't make subscribtion without firstChild, so when you actually navigate to firstChild, subscribtion won't trigger.

My version will create subscription, that will filter valid events. Mind you, this would most likely be better way of doing it: https://stackoverflow.com/a/48979356/1980151

this.route.params.subscribe(() => {
    if (this.route.firstChild && this.route.firstChild.snapshot.params['folderId']) {
        this.folderId = +this.route.firstChild.snapshot.params['folderId'];
    }
});
Gonzi
  • 77
  • 2
  • 7