Open new window in new tab

前端 未结 1 1409
北荒
北荒 2020-12-14 00:18

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\')         


        
相关标签:
1条回答
  • 2020-12-14 01:11

    The reason for window variable being undefined is the fact that you have declared a variable named window again in the local scope.

    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');
    

    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

    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

    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);
        })
    }
    
    0 讨论(0)
提交回复
热议问题