'this' 在 subscribe 内未定义 [英] 'This' is undefined inside subscribe

查看:45
本文介绍了'this' 在 subscribe 内未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 subscribe 语句,我正在尝试调试它,但是当我逐步执行 VS Code 时,语句中的this"始终未定义.在这种情况下,'this.dataLoaded' 是未定义的.调试时如何让它不被未定义?

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){
                      ...
                    }
                });  

推荐答案

当您使用 .subscribe() 时,在 angular 中可能无法获得 this代码>.在我的情况下,我使用了另一个副本.它总是对我有用.它也可能适合你.

When you are using .subscribe() then in angular it may possible that it'll not getting this. In my case I used another replica of this. It always works for me. It may for you also.

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
                  ...
                }
            }); 

这篇关于'this' 在 subscribe 内未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆