I'm new to Angular and still learning it.
I have a component which subscribes to the router NavigationEnd event which accesses some variables initialized in a route resolve from a service.
constructor(private route: ActivatedRoute, private router: Router) {
var that = this;
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
}
});}
When I debug the code the this.nominatim variable is undefined but it does contain a value that I can log to the console.
I have found another question on stackoverflow which explains a similar sitution 'This' is undefined inside subscribe
By adding
var that = this;
before the router event subscription I can see the variables in debug.
I would prefer it if I could still use the 'this' context.
How can I get this to work?
First of all you should not be subscribing inside the constructor. Angular docs recommend that all work (except very light variable assignment) is done inside ngOnInit - to be safe you should never use the constructor other than for dependency injection.
If you move your code to ngOnInit you may find that "this" works. ngOnInit is an Angular lifecycle hook and is called automatically very soon after the constructor.
Failing that, you can call a method inside ngOnInit like so:
ngOnInit() {
this.myCodeToSubscribeToRouterEvents()
}
private myCodeToSubscribeToRouterEvents() {
// TODO: Paste your subscription code here
}
Then in the constructor you can write:
constructor(private route: ActivatedRoute, private router: Router) {
this.myCodeToSubscribeToRouterEvents = this.myCodeToSubscribeToRouterEvents.bind(this);
}
Yes I know I am putting code in the constructor when I just said not to, but this is one of the rare exceptions. This constructor code ensures that inside myCodeToSubscribeToRouterEvents "this" is always an instance of the component (which is what you want) and not something else.
Hope it helps. J.E.S.U.S loves you :D
Regarding:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.nominatim);
You will be better off with:
this.nominatim = this.route.snapshot.data.meetings.nominatim;
console.log(this.route.snapshot.data);
So you can check the data is coming through :)