Skip to content

Instantly share code, notes, and snippets.

@patrickarlt
Created October 16, 2018 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickarlt/09dc3d388af72dac7d80c2acca425f98 to your computer and use it in GitHub Desktop.
Save patrickarlt/09dc3d388af72dac7d80c2acca425f98 to your computer and use it in GitHub Desktop.
An Angular service wrapping esri-loader for use

This is used as a custom resolver on the route you want to load the JS API modules on as per https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html.

you can then access the modules by injecting ActivatedRoute into your component and looking at this.route.snapshot.data['esri']['Map'].

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { EsriModuleResolveService } from "./esri-module-resolve.service";
import { MapViewComponent } from "./map-view.component"; 

const routes: Routes = [
      {
        path: "map",
        component: MapViewComponent,
        resolve: { esri: EsriModuleResolveService },
        data: {
          esriModules: {
            Map: "esri/Map",
            MapView: "esri/views/MapView",
            FeatureLayer: "esri/layers/FeatureLayer",
            Legend: "esri/widgets/Legend"
          }
        }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MyRoutingModule {}
import { Injectable } from "@angular/core";
import { Resolve, ActivatedRouteSnapshot } from "@angular/router";
import { loadModules } from "esri-loader";
@Injectable()
export class EsriModuleResolveService implements Resolve<any> {
private scriptsLoaded: boolean;
resolve(route: ActivatedRouteSnapshot): Promise<any> {
let modules = route.data["esriModules"];
let moduleKeys = Object.keys(modules);
let moduleNames = moduleKeys.map(key => modules[key]);
return loadModules(moduleNames, {
url: "https://js.arcgis.com/4.9/"
}).then(functions => {
let loadedModules: any = {};
moduleKeys.forEach((key, index) => {
loadedModules[key] = functions[index];
});
if (!this.scriptsLoaded) {
this.loadCss();
this.loadConfig();
this.scriptsLoaded = true;
}
return loadedModules;
});
}
private loadCss() {
let link = document.createElement("link");
link.href = "https://js.arcgis.com/4.9/esri/css/main.css";
link.rel = "stylesheet";
document.head.appendChild(link);
}
private loadConfig() {
let script = document.createElement("script");
script.type = "text/javascript";
script.src = "/assets/js/config-js-api-4.js";
document.body.appendChild(script);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment