【发布时间】:2016-11-01 15:22:17
【问题描述】:
我有一个 Angular2 应用程序,我已经向在 ng2 之外运行的代码公开了某些方法。问题是 this 在 ng2 外部和内部调用时不一样。
https://plnkr.co/edit/KZeH1ArvuMTmsBCFjNnY (观察控制台看看发生了什么)
在我的应用组件中,它在加载时将名称设置为“Angular2”。我有一个简单的this.name = "modified angular2 app 的doSomething 方法。当我通过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