【问题标题】:'This' is undefined inside subscribe'This' 在订阅中未定义
【发布时间】:2019-03-29 05:05:44
【问题描述】:

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

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

【问题讨论】:

  • 你能展示周围的代码,或者链接到stackblitz的完整解决方案吗?这里没什么可做的。
  • 很可能在编译过程中被改写为_this或类似的东西。查看调试界面的“Locals”或“Scope”部分并查找范围内的其他项目。
  • 嗨 Terrance 是正常的,因为你在 this 这是事件而不是全局范围 this 中,尝试 this const me = this ,在 this.router 之外,然后 !me.dataLoaded
  • @AmericoArvani 没有本地 this,因为 subscribe 正在使用箭头函数。
  • 更正本地 this 仅在调试时未定义。如果代码只是运行,它工作正常。我只需要知道是否有一种方法可以在调试时在订阅中看到本地“this”。 @Daniel Giminez 没有周围的代码。这可能是一天的面试问题

标签: angular typescript visual-studio-code


【解决方案1】:

当您使用 .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
                  ...
                }
            }); 

【讨论】:

  • 我偶然发现了这个,你能解释一下为什么吗?
  • 请参阅下面 My Stack Overfloweth 的回复 - 这/这不再是推荐路线
  • @ParsaGachkar 的答案应该是被接受的。
  • 正如 My Stack Overfloweth 所回答的,现在有一种更好的方法可以使用箭头函数来执行此操作。这是目前解决该问题的最佳方法。
【解决方案2】:

请查看closure 在调试器variables 选项卡中展开部分。您真正的this 将比最顶层高一级,其中this 指的是组件控制器名称。每个匿名函数都会创建额外的闭包,在您的情况下,它包含在 subscribe 中,当您的断点被命中时,VS Code 默认会打开此闭包。

请尽量避免这种老式的 JS hack let that = this e.c.t,因为当您使用 TypeScript、Classes、ES6 和箭头函数时,这些 hack 就不再需要了。

【讨论】:

    【解决方案3】:

    我不确定这是不是个好主意。我是初学者。但你可以使用.bind(this) 方法。

    这是一个角度 ts 示例:

    this.myService.getData().subscribe((data=>{
        this.doSomething(data);
        alert(this.somethingElse);
    }).bind(this));
    

    【讨论】:

      【解决方案4】:

      作为接近从接受的答案实施that = this 路线的人,请保存自己并查看托马斯写的答案。如果可能的话,最好花一些额外的时间并避免使用 javascript hack。

      有关使用箭头函数保持this 上下文的示例,请参见下文。

      这是我最初丢失this 上下文的代码:

      this.settingsService.getClientSettingsByCategory(clientId, categoryId)
          .subscribe(
              this.loadJobStatusReport
          );
      

      这是保持预期 this 上下文的更新代码:

      this.settingsService.getClientSettingsByCategory(clientId, categoryId)
          .subscribe(
              settings => this.loadJobStatusReport(settings)
          );
      

      【讨论】:

      • 你通过什么设置?
      • 我们的“getClientSettingsByCategory”方法的返回值。这是一个“设置”对象的数组。
      • 完美 - 这是有道理的。感谢您明确表示,尤其是在那个/这个辩论中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2018-05-14
      相关资源
      最近更新 更多