【问题标题】:Access Angular2 app through window loses scope of "this"通过窗口访问 Angular2 应用程序失去了“this”的范围
【发布时间】:2016-11-01 15:22:17
【问题描述】:

我有一个 Angular2 应用程序,我已经向在 ng2 之外运行的代码公开了某些方法。问题是 this 在 ng2 外部和内部调用时不一样。

https://plnkr.co/edit/KZeH1ArvuMTmsBCFjNnY (观察控制台看看发生了什么)

在我的应用组件中,它在加载时将名称设置为“Angular2”。我有一个简单的this.name = "modified angular2 appdoSomething 方法。当我通过window.myVar.doSomething() 调用它时,this 的范围不是我的类,它是我暴露的对象。如何访问name。我在构造函数中尝试了self = this 并执行self.name = ,但是当我捆绑并缩小以进行生产时它失败了。

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;

  constructor() {
    this.name = 'Angular2'
  }

  doSomething(){
    this.name = "modified angular2 app" 
  }

  ngOnInit() {

    window.myVar = {doSomething:this.doSomething}

  }

}

在我的 index.html 中,我添加了一个 sn-p 来调用我的 doSomething 方法。

<body>
    <my-app>
    loading...
  </my-app>
  <script>
    function checkReady() {
      if (window.myVar) {
        console.log("Ready")
        console.log(myVar)
        myVar.doSomething();
      } else {
        setTimeout(function() {
          console.log("Not ready")
          checkReady()
        }, 500)
      }
    }
    checkReady()
  </script>
  </body>

【问题讨论】:

    标签: javascript angular typescript angularjs-scope this


    【解决方案1】:

    您需要bind() 函数的上下文。这样,无论从哪里调用它,它都可以访问声明它的局部变量。

    window.myVar = { doSomething: this.doSomething.bind(this) };
    

    【讨论】:

      【解决方案2】:

      TypeScript 具有粗箭头语法,您可以使用它来自动将this 绑定到类实例:

      export class App
      {
        //...
        doSomething = () => {
          this.name = "modified angular2 app" 
        }
        //...
      }
      

      请注意,此语法会导致函数 doSomething 不再是 App 原型的一部分。

      关于this in typescript/javascript here 的更多信息,以及不同策略的优缺点。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2013-06-05
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多