我有一个 Angular2 应用程序,我已将某些方法公开给在 ng2 之外运行的代码。问题是 this
在 ng2 外部调用与内部调用时不一样。
https://plnkr.co/edit/KZeH1ArvuMTmsBCFjNnY (观察控制台看看发生了什么)
在我的应用程序组件中,它在加载时将名称设置为“Angular2”。我有 doSomething
方法,它执行一个简单的 this.name = "modified angular2 app
。当我通过 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
中,我添加了一个代码片段来调用我的 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>
最佳答案
您需要将您的上下文bind()
到该函数。这样,无论从哪里调用它,它都可以访问声明它的局部变量。
window.myVar = { doSomething: this.doSomething.bind(this) };
关于javascript - 通过窗口访问 Angular2 应用程序丢失了 "this"的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40363118/