'This' 在 subscribe 中未定义

Ter*_*son 6 typescript visual-studio-code angular

我有一个订阅语句,我正在尝试调试它,但是当我在 VS Code 中单步执行时,“this”在语句内始终未定义。在这种情况下,“this.dataLoaded”未定义。调试时如何使其不为未定义?

this.router.events
            .filter(event => (event instanceof NavigationEnd))
                .subscribe((routeData: any) => {                        
                    if(!this.dataLoaded){
                      ...
                    }
                });  
Run Code Online (Sandbox Code Playgroud)

Sac*_*hah 3

当您在角度中使用.subscribe()then 时,它可能不会得到this. 就我而言,我使用了另一个复制品。它总是对我有用。它也可能适合你。

var that = this; // Hear I store the this ref into another that
this.router.events
        .filter(event => (event instanceof NavigationEnd))
            .subscribe((routeData: any) => {                        
                if(!that.dataLoaded){  // Hear you can use that instead of this
                  ...
                }
            }); 
Run Code Online (Sandbox Code Playgroud)

  • 请参阅下面 My Stack Overfloweth 的回复 - 那/这不再是推荐的路线 (2认同)