angular2-useful-swiper icon indicating copy to clipboard operation
angular2-useful-swiper copied to clipboard

Angular Universal (server) running code it should not

Open aljazerzen opened this issue 7 years ago • 4 comments

When running this module on Node.js (for server-side rendering) I get an error

Reference error: Swiper not defined

in this line.

As the comment says right above, this code should never even been run on the server in the first place. Is it possible that this.elementRef.nativeElement.querySelector is not undefined?

PS: for anyone encountering this error: my workaround was to run a script that replaces this if(this.elementRef.nativeElement.querySelector) { line with if(false) {

aljazerzen avatar Feb 13 '18 14:02 aljazerzen

@aljazerzen did you import swiper.min.css and swiper.js files? if not, please include these files in index.html

<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/css/swiper.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.4.2/js/swiper.js"></script>

ghost avatar Mar 09 '18 16:03 ghost

Yes these files were imported, but as a part of Angular application as so:

// .angular-cli.json
...
    {
      "platform": "server",
      ...
      "scripts": [
        "../node_modules/swiper/dist/js/swiper.js",
        ...
      ],
    },
  ],

Swiper worked as intened, only when bundling to be run on the server for SSR, mentioned if statement was not working properly.

aljazerzen avatar Mar 09 '18 18:03 aljazerzen

Workaround is to run the initialisation, only when it is in the browser mode.

in thecontroller

if (isPlatformBrowser(this.platformId)) { this.swipperisActive = true; }

in the template :

<swiper [config]="config" class="swiper-container" [initialize]="swipperisActive">

Tested and working

anymos avatar May 24 '18 05:05 anymos

add platform check for setup function https://github.com/JayChase/angular2-useful-swiper/pull/56

Gorniv avatar Oct 15 '18 13:10 Gorniv