如何在angular2中的新选项卡中打开新窗口
发布时间:2020-12-17 09:41:30 所属栏目:安全 来源:网络整理
导读:当用户点击按钮时,我试图打开一个新窗口 protected assignActity(type: string): void { var window = window.open('/#/link'); this.Service.assignActivity(type).subscribe(res = { window.location = '/#/link/' + res; console.log(res); }) } 但它抛出
当用户点击按钮时,我试图打开一个新窗口
protected assignActity(type: string): void { var window = window.open('/#/link'); this.Service.assignActivity(type).subscribe(res => { window.location = '/#/link/' + res; console.log(res); }) } 但它抛出一个错误, core.umd.js:3468 TypeError: Cannot read property 'open' of undefined 请纠正我的工作.
窗口变量未定义的原因是您已经在本地作用域中再次声明了一个名为window的变量.
根据javascript / typescript的范围规则,在访问全局变量之前,会查找局部变量值. 所以您只需更改捕获打开的选项卡引用的变量名称即可 var newWindow = window.open('some_url'); 然而,这不是推荐的方法,因为angular2应用程序可以在各种环境中运行,例如移动或在窗口对象可能不可用的情况下呈现服务器端.更不用说在测试中模拟窗口对象很难 相反,您可以将窗口对象包装在服务中,并将该服务注入到组件中.这样,您可以根据环境简单地替换服务实现,使用依赖注入 ---- the service file ---- @Injectable() export class WindowRef { constructor() {} getNativeWindow() { return window; } } ----- the component file----- @Component({ selector : 'demo',template : '<div> Demo </div>' }) class DemoComponent { nativeWindow: any constructor( private winRef: WindowRef ) { this.nativeWindow = winRef.getNativeWindow(); } protected assignActity(type: string): void { var newWindow = this.nativeWindow.open('/#/link'); this.Service.assignActivity(type).subscribe(res => { newWindow.location = '/#/link/' + res; console.log(res); }) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |