0

I have a variable in a component with a predefined value path.

After upgrading from Angular 6.0 to 6.1.7, it is showing as undefined

export class AppComponent implements OnInit {
  path: string = '/';

  constructor(public route: Router) {
    console.log(this.path)
  }

  ngOnInit() { 
    this.route.events.subscribe((route)=>{
      this.path = (route as any).url;
    })
    this.getFeatured();
  }
}

Statement causing error in template:

*ngIf="!path.includes('/reports') && !path.includes('/reviews') && !path.includes('/users')"

I do not think its an async issue since it logs it into the console:

enter image description here

2
  • Is that the template of the AppComponent component or is it the template of a different one? Commented Sep 11, 2018 at 21:13
  • @Danziger Yep, when I commented out that piece of code and everything start to work Commented Sep 11, 2018 at 21:16

1 Answer 1

3

Well after I traced your code, this happens because simply the subscription is for an event rather than a route (Of course the naming wouldn't matter, just the semantics).

So the last event that fires in the cycle of navigation, is a scrollEvent, which doesn't contain a key url, thus resulting in undefined.

I think you will need to check the type of the event fired to be of type NavigationEnd by doing something like that :

this.route.events.subscribe((event)=>{
    if(event instanceof NavigationEnd){
      this.path = (event as any).url;
    }
})

Edit:

Here is the log to understand what I meant exactly, the latest event (or for fact might be any event in a bigger application), might not contain the url property : enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the informative answer.. But it still doesn't seem to work. I removed the route.events.subscribe() code block entirely and seem to still face this issue. Now all I have is a defined string
Oh man, I'm not sure then. Does it work fine but just throwing a console error ? if yes you can use path?.includes() ? If you can share more code maybe there's something missing
Oh it seems to be working. But now I get Cannot find name 'NavigationEnd'.
That's just typescript missing the import, add import { Router, NavigationEnd } from '@angular/router'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.