window
变量为undefined
的原因是you have declared a variable named window again in the local scope.
根据javascript/typescript
的范围规则,在访问全局变量之前,将查找局部变量值.
因此,您所要做的只是更改捕获打开的选项卡引用的变量名
var newWindow = window.open('some_url');
但是,这不是推荐的方法,因为angular2应用程序可以在各种环境中运行,例如移动或渲染服务器端,其中window
个对象可能可用,也可能不可用.更不用说在测试中模拟窗口对象是非常困难的
相反,您可以将window
对象包装在一个服务中,并将该服务注入到您的组件中.通过这种方式,您可以根据环境简单地使用Dependency injection替换service实现
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);
})
}