Angular Universal: navigator is not defined

Issue

I followed official angular-cli tutorial to integrate angular-universal to my existing angular-cli app.

I am able to do SSR for my angular-cli app. But when I try to integrate ngx-leaflet, I am getting following error:

ReferenceError: navigator is not defined
at D:\ng2-ssr-pwa\dist\server.js:40251:29

Now, I understand that leaflet is trying to access navigator object which is not available in the Node context. So I decided to delay leaflet rendering until the page is loaded in the browser as given in this SO thread.
But still I am getting same error. You can look the demo app with leaflet issue here.

./src/app/browserModuleLoader.service.ts:

import { Component, Inject, Injectable, OnInit, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

@Injectable()
export class BrowserModuleLoaderService {
    private _L: any;

    public constructor(@Inject(PLATFORM_ID) private _platformId: Object) {
        this._init();
    }

    public getL() {
        return this._safeGet(() => this._L);
    }

    private _init() {
        if (isPlatformBrowser(this._platformId)) {
            this._requireLegacyResources();
        }
    }

    private _requireLegacyResources() {
        this._L = require('leaflet');
    }

    private _safeGet(getCallcack: () => any) {
        if (isPlatformServer(this._platformId)) {
            throw new Error('invalid access to legacy component on server');
        }

        return getCallcack();
    }
}

./src/app/leaflet/app/leaflet.component.ts:

// import * as L from 'leaflet';

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, PLATFORM_ID } from '@angular/core';

import { BrowserModuleLoaderService } from '../browserModuleLoader.service';
import { isPlatformBrowser } from '@angular/common';

@Component({
    selector: 'app-leaflet',
    styleUrls: ['./leaflet.component.scss'],
    template: `
      <div  *ngIf="isBrowser">
        <div leaflet [leafletOptions]="options"></div>
        </div>
  `,
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LeafletComponent {
    isBrowser: boolean;
    options = {};

    constructor(private cdr: ChangeDetectorRef,
        @Inject(PLATFORM_ID) platformId: Object,
        private browserModuleLoaderService: BrowserModuleLoaderService
    ) {
        this.isBrowser = isPlatformBrowser(platformId);
    }

    ngAfterViewInit() {
        console.log('this.isBrowser ', this.isBrowser);
        if (this.isBrowser) {
            const L = this.browserModuleLoaderService.getL();
            this.options = {
                layers: [
                    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' }),
                ],
                zoom: 5,
                center: L.latLng({ lat: 38.991709, lng: -76.886109 }),
            };
        }
        this.cdr.detach();
    }

}

./src/app/app.component.html:

<div>
  <app-leaflet></app-leaflet>
</div>

How do I safely delay the leaflet rendering until the platform is not browser?

EDIT:

I removed all code related to leaflet (browserModuleLoader.service.ts, leaflet.component.ts ect. ) and kept only leaflet module import in app.module.ts and actually this import is causing issue.

./src/app/app.module.ts:

import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
// import { BrowserModuleLoaderService } from './browserModuleLoader.service';
// import { LeafletComponent } from './leaflet/leaflet.component';
import { LeafletModule } from '@asymmetrik/ngx-leaflet';
import { NgModule } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent,
    // LeafletComponent
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'my-app'}),
    LeafletModule.forRoot()
  ],
  providers: [
    // BrowserModuleLoaderService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

./src/app/app.server.module.ts:

import {AppComponent} from './app.component';
import {AppModule} from './app.module';
import {ModuleMapLoaderModule} from '@nguniversal/module-map-ngfactory-loader';
import {NgModule} from '@angular/core';
import {ServerModule} from '@angular/platform-server';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ModuleMapLoaderModule
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

How do I handle this nxg-leaflet module import?

Solution

Solved this issue by using Mock Browser.

server.ts:

const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();


global['navigator'] = mock.getNavigator();

Answered By – Saurabh Palatkar

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.