【问题标题】:How to access global typescript variable from anonymous function如何从匿名函数访问全局打字稿变量
【发布时间】:2017-08-24 21:25:55
【问题描述】:

我有一个 Angular2 应用程序,我想在用户关闭浏览器窗口时执行一些逻辑。我正在使用浏览器窗口的 beforeunload 事件。我在我的 TypeScript 类构造函数中放置了以下代码:

export class MyAngularComponent implements OnInit, OnDestroy {  

  callServer()
  {
     //Logic to call the server
  }

  constructor(private updateServiceFactory: UpdateService) {

    window.onbeforeunload = function(e){
      this.callServer();  //this does not work            
    }
  }
}

我在 this.callServer() 行中收到编译错误。错误显示“类型 'Window' 上不存在属性 'callServer'”。我知道匿名函数上下文中的“this”指的是 Window 对象。

问题:如何从匿名函数内部调用 callServer() 方法?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    使用箭头函数而不是简单函数。箭头函数从声明上下文中捕捉到这一点。

    export class MyAngularComponent implements OnInit, OnDestroy {  
    
      callServer()
      {
         //Logic to call the server
      }
    
      constructor(private updateServiceFactory: UpdateService) {
    
        window.onbeforeunload = (e) => {
          this.callServer();  //this now refers to MyAngularComponent             
        }
      }
    }
    

    【讨论】:

    • 有人愿意评论他们为什么投反对票吗?想知道问题是什么,也许我可以解决它:)
    • 我的答案和问题也被否决了,所以我怀疑有人只是出于某种原因盲目地对所有内容投了反对票(其他答案尚未发布)。
    • @Diopside 有一点,如果 Angular 提供了一种监听主机事件的方法,最好使用它:)
    【解决方案2】:

    尝试在您的组件中使用 HostListener,而不是在构造函数中。

     @HostListener('window:beforeunload', ['$event'])
     doSomething($event) {
         // your code here //
     }
    

    除了与传递给构造函数的参数直接相关的事情之外,构造函数通常不是一个好地方。

    【讨论】:

    • 这和公认的答案一样有效,但 Titan 是第一个。
    【解决方案3】:

    您可以使用bind 将函数的this 更改为正确的上下文。

    window.onbeforeunload = function(e){
      this.callServer();
    }.bind(this)
    

    【讨论】:

    • 这和公认的答案一样有效,但 Titan 是第一个。
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多