2017-06-29 52 views
0

我有一个创建iframe的角度服务。现在,在这个iframe的onLoad上,我想调用一些相同服务的功能。如何以编程方式创建的iframe的onLoad调用this.somefunction()?

private createIframe() { 
    let iframe = document.createElement('iframe'); 
    iframe.onload = function() { this.somefunction();} 
    iframe.style.display = 'none'; 
    this.aAuthService.createLoginUrl('').then(function (url) { 
     iframe.src = url; 
    }); 
    document.body.appendChild(iframe); 
} 

private somefunction() {...} 

我收到错误说 “somefunction上不存在HTMLIframeElement”。

如何在动态创建iframe时从onload调用somefunction()?

回答

1

事情是这样的:

iframe.onload = function() { this.somefunction();} 

现在,this没有指向您的服务类,但它实际上是指向匿名函数,所以要么你必须绑定this匿名功能范围,所以这.somefunction指向类方法,而不是指向特定于内部的属性(不存在),或者使用胖箭头函数,因为胖箭头函数引用词法作用域而不是本地函数作用域。

iframe.onload =() => this.somefunction() 

这应该这样做。