首页 > 解决方案 > Angular universal

问题描述

I'm using Mapkitjs to create a map, and it initialized via window object, on the server i see error

TypeError: Cannot read property 'init' of undefined

How i can add script into the server for fix that error? I tried

const win = domino.createWindow(template);
const script = win.document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js';
win.document.body.appendChild(script);

But it doesn't work

标签: angularangular-universal

解决方案


Just bypass the server side as it does not support DOM-associated stuffs.

Example:

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

...
isBrowser: boolean;

constructor(
  @Inject(PLATFORM_ID) private platformId
) {
  this.isBrowser = isPlatformBrowser(this.platformId);
}

...

if (this.isBrowser) {
  // Put your code here
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js';
  document.body.appendChild(script);
}


推荐阅读