Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'This' is undefined inside subscribe

I have a subscribe statement and I am trying to debug this however when I step through in VS Code 'this' is always undefined inside the statement. In this situation 'this.dataLoaded' is undefined. how can I get it to not be undefined when debugging?

this.router.events
            .filter(event => (event instanceof NavigationEnd))
                .subscribe((routeData: any) => {                        
                    if(!this.dataLoaded){
                      ...
                    }
                });  
like image 639
Terrance Jackson Avatar asked Mar 06 '23 05:03

Terrance Jackson


1 Answers

Please have a look on closure expand sections in debugger variables tab. Your real this will be one level above the top-most, where this is referred to component controller name. Each anonymous function creates additional closure, in your case it's enclosed in subscribe, ant this closure will be opened by default by VS Code when your breakpoint will be hit.

And please try to avoid this old-style JS hacking let that = this e.c.t, because when you on TypeScript, Classes, ES6 and arrow functions those hacks are just not needed anymore.

like image 87
Tomas Avatar answered Mar 11 '23 23:03

Tomas