evertonrobertoauler / universal-demo-v5

26 stars 14 forks source link

How can we access window, navigator and DOM elements since we are rendering server side? #3

Closed fott1 closed 6 years ago

fott1 commented 6 years ago

Great work with your tutorial, but i am struggling to dist/server my app since i frequently use browser "things". Is there any proper way to make it work? I use localStorage, cookies and window in some places.

evertonrobertoauler commented 6 years ago

Hi, you can't use browser things when your code is running on the server, but you can do something like this:

 import { PLATFORM_ID } from '@angular/core';
 import { isPlatformBrowser, isPlatformServer } from '@angular/common';

 constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }

 ngOnInit() {
   if (isPlatformBrowser(this.platformId)) {
      // Client only code.
      ...
   }
   if (isPlatformServer(this.platformId)) {
     // Server only code.
     ...
   }
 }