javascript - Angular 通用 : navigator is not defined

标签 javascript angular angular-cli angular-universal ngx-leaflet

我关注官方angular-cli tutorial将 angular-universal 集成到我现有的 angular-cli 应用程序中。

我可以为我的 angular-cli 应用程序执行 SSR。但是当我尝试整合 ngx-leaflet ,我收到以下错误:

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

现在,我了解到 leaflet 正在尝试访问节点上下文中不可用的导航器对象。所以我决定延迟传单呈现,直到页面加载到浏览器中,如本 SO thread 中所示. 但我仍然遇到同样的错误。您可以查看带有传单问题的演示应用程序 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>

我如何安全地延迟传单呈现,直到平台不是浏览器?

编辑:

我删除了所有与 leaflet 相关的代码(browserModuleLoader.service.ts、leaflet.component.ts 等),只在 app.module.ts 中保留了 leaflet 模块导入,实际上这个导入导致了问题。

./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 {}

我如何处理这个 nxg-leaflet 模块导入?

最佳答案

使用 Mock Browser 解决了这个问题.

server.ts:

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


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

关于javascript - Angular 通用 : navigator is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49838859/

相关文章:

node.js - npm 更新后 angular-cli 构建错误

对象函数的 JavaScript 名称

angular - 如何将异步数据作为对象数组传递给子组件 - angular 6

angular - 如何检测 ion-content 是否有滚动条?

javascript - 导入 OAS 生成的 api 时 angular 8 崩溃

angular - 如何升级 Angular CLI 项目?

javascript - Eloquent javascript 第 4 章数组

javascript - 如何在原生 JavaScript 中阻止 Sprite 从 Canvas 上移出?

javascript - Vuetify.js Datepicker - 提供允许日期的数组?

javascript - Angular CLI - 如何在整个应用程序中共享原型(prototype)函数