The reason why the window
variable is coming up as undefined
is due to the fact that you have redefined a variable named window in the local scope.
Based on the scoping rules of javascript/typescript
, the value of local variables is checked before accessing the global variable. Additionally, when a variable is first declared, it is automatically set to undefined, which explains the error message you are encountering.
To resolve this issue, all you need to do is change the name of the variable where you store the reference to the opened tab
var newWindow = window.open('some_url');
However, this method is not ideal for angular2 apps as they can operate in various environments like mobile devices or server-side rendering where the availability of the window
object may vary. Moreover, mocking the window object for testing purposes would be quite challenging.
Instead, you can encapsulate the window
object within a service and inject that service into your component. This allows you to easily swap out the service implementation based on the environment using Dependency Injection
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);
})
}