6

I am using arcgis-js-api types in my angular5 application. When i try to import the types in multiple components i am getting uncaught reference error: __esri is not defined. I have included arcgis-js-api to the types array in tsconfig.app.json file. Here is my code.

  import { Component, OnInit, Input, ViewChild, ElementRef } from 
'@angular/core';
  import * as esriLoader from 'esri-loader';
  import { environment } from '../../../environments/environment';
  import Esri = __esri;

  @Component({
    selector: 'app-custom-widget',
    templateUrl: './custom-widget.component.html',
    styleUrls: ['./custom-widget.component.css']
  })
  export class CustomWidgetComponent implements OnInit {
    private _mapView: Esri.MapView;
    private _scriptOptions: any;

    @ViewChild('customWidget') widgetElement: ElementRef;
    @Input()
    set mapView(mapView: Esri.MapView) {
      if (!mapView) {
        return;
      }
      this._mapView = mapView;
      this.renderWidget();
    }
    get mapView(): Esri.MapView {
      return this._mapView;
    }

    constructor() {
      this._scriptOptions = {
        url: environment.arcgisAPIVersion
      };
    }

    ngOnInit() {

    }

    renderWidget(): void {
      esriLoader.loadModules([
        'esri/widgets/Widget'
      ], this._scriptOptions).then(([Widget]) => {
        const widgetProperties: Esri.WidgetProperties = {
          container: this.widgetElement.nativeElement
        };

        const widget: Esri.Widget = new Widget(widgetProperties);

        this._mapView.ui.add(widget, 'bottom-right');
      });
    }

  }
  • 1
    You didn't load `__esri` but you did use it. That's why you get an error. – Aluan Haddad Mar 18 '18 at 19:28
  • 2
    The problem is inherent in expressing dependencies via global variables and has nothing to do with TypeScript. Note that this is a runtime error. – Aluan Haddad Mar 18 '18 at 19:30
  • @Aluan Hadded: If i didn't load __esri it should not work in other component as well. I see this is happening when __esri namespace is used in multiple components. – Bharath Konaganti Mar 19 '18 at 02:25
  • Were you able to solve this issue? I also get the same error when I attempt to use the __esri namespace in more than one component. – mfcallahan Apr 13 '19 at 22:04

1 Answers1

0

I found that this solution is what worked for me-
I created one models file that imports the namespace and then I used the types wherever I needed (effectively evading the bug "ReferenceError: __esri is not defined, cannot use this namespace in multiple components").

example:
In esri.models.ts file-

import esri = __esri;  
export interface esriMapView extends esri.MapView {}
export interface esriLayerView extends esri.LayerView {}

In components-

import { esriMapView } from "../../modules/esri.models";
const mapView: esriMapView = new MapView({});
Shaked
  • 93
  • 1
  • 9