Angular 4 Universal “window is not defined”

前端 未结 3 1665
故里飘歌
故里飘歌 2021-01-18 19:20

My project was running perfectly but when i implement universal then i am getting \"window is not defined\".

My error is as below.

 node_modules/hamm         


        
相关标签:
3条回答
  • 2021-01-18 20:14

    You can use @squadette/hammerjs instead of hammerjs. @squadette/hammerjs is server side render friendly.

    To use it, just run

    npm i @squadette/hammerjs 
    

    to instal it. then replace change

    import  'hammerjs';
    

    to

    import  '@squadette/hammerjs';
    
    0 讨论(0)
  • 2021-01-18 20:16

    Because Angular Universal allows you to create server-side rendered pages. And in a server, you don't have a browser, therefore you don't have a window.

    You should make a condition to test if the window exists, something like this

    if (window) { /* do your window things here */}
    
    0 讨论(0)
  • 2021-01-18 20:18

    As @trichetriche said. You don't have access to window object on the server side. The only thing which should be mentioned here is, that the better way instead of using

    if(window) {}
    

    Would be (let's say it is more "Angular" ;) ):

    import { isPlatformBrowser, isPlatformServer } from '@angular/common';
    import { Inject, PLATFORM_ID } from '@angular/core';
    
    constructor(@Inject(PLATFORM_ID) private platformId: any) {}
    
    public someMethod(): boolean {
        if (isPlatformBrowser(this.platformId)) {
             //action specific for browser
        }
    }
    

    You can take a look at live example in one of my repositories: https://github.com/maciejtreder/angular-universal-pwa/blob/master/src/app/services/notification.service.ts

    0 讨论(0)
提交回复
热议问题