angular - 'This' 在 subscribe 中未定义

标签 angular typescript visual-studio-code

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

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

最佳答案

当您使用.subscribe()时,在 Angular 中它可能不会得到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
                  ...
                }
            }); 

关于angular - 'This' 在 subscribe 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974811/

相关文章:

asp.net-core - 无法在 Visual Studio Code 中为 EntityFrameworkCore 添加迁移

c# - 通过 vsdbg 在 vscode 中运行 C# 时,有没有办法关闭 DLL 加载消息?

tabs - 如何让 VS Code 编辑器选项卡在左侧关闭?

html - 我们如何从头开始以 Angular 创建模态弹出窗口

angular - 通过 Angular 2 路由传递动态数据

typescript - 将两种类型关联在一起

typescript - 从接口(interface)扩展以添加新属性会导致 "Type X is not generic"

css - 如何垂直居中 input/textarea 元素,其中多行文本仍环绕在下方?

cordova - 从 ionic2 访问打印机

angular - 类型 ClassB 中的属性 x 不可分配给基类型 ClassA 中的相同属性