在新标签中打开新窗口 [英] Open new window in new tab

查看:24
本文介绍了在新标签中打开新窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击按钮时,我正在尝试打开一个新窗口,如下所示:

I am trying to open a new window when user click on button as follows:

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

如何纠正它以使其正常工作?

How to correct it to get it working?

推荐答案

window变量为undefined的原因是你已经声明了一个变量在本地范围内再次命名窗口.

根据javascript/typescript的作用域规则,在访问全局变量之前,先查找局部变量的值.此外,当您最初声明一个变量时,它被设置为未定义,因此您会收到错误消息.

According to the scoping rules of javascript/typescript, before the global variable is accessed, the local variables value is looked up. Also when you initially declare a variable, it is set to undefined, Hence the error message you receive.

所以你所要做的只是改变你捕获打开标签的引用的变量名

So all you have to do is simply change the variable name in which you capture the opened tab's reference

var newWindow = window.open('some_url');

但这不是推荐的方法,因为 angular2 应用程序可以在各种环境中运行,例如移动或呈现服务器端,其中 window 对象可能可用也可能不可用.更不用说在测试中模拟窗口对象会非常困难

However this is not the recommended approach as angular2 apps can run in a variety of environments such as mobile or be rendered server side where window object may or may not be available. Not to mention it would be very hard to mock the window object in tests

相反,您可以将 window 对象包装在服务中,并将该服务注入到您的组件中.这样您就可以根据环境简单地替换 service 实现,使用 依赖注入

Instead you can wrap the window object in a service and inject that service into your component. This way you can simply substitute the service implementation according to the environment, using Dependency injection

服务文件

@Injectable()
export class WindowRef {
    constructor() {}

    getNativeWindow() {
        return window;
    }
}

组件文件

@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);
    })
}

这篇关于在新标签中打开新窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆