Angular Injectable服务依赖于DOM元素

时间:2018-06-01 19:05:11

标签: javascript angular angular6 esri-javascript-api

我正在抓住Angular(6)框架,这是它的怪癖和特征。 并且有一件事,我需要,但是看起来,它违背了Angular范例 - 一个需要引用DOM节点的服务。

更具体地说 - Esri Map component。 在它的构造函数中,它需要一个DOM节点 - 一个地图将存在的地方。 由于Map将成为应用程序中的中心,因此整个应用程序中的多个组件都会使用它。为此,我希望它能在服务中使用。问题是 - 我该怎么做?我解决了这个问题,但我想与更有经验的Angular开发人员进行验证。

所以我有一个MapComponent就像一个单例组件 - 只在App中包含一次。

export class MapComponent implements OnInit {
  @ViewChild('map') mapElement:ElementRef;
  constructor(
    private renderer2: Renderer2,
    private mapService: MapService) { }
  ngOnInit() {
    // This is where I pass my DOM element to the service, to initialize it
    this.mapService.init(this.mapElement.nativeElement);
  }
}

我的mapService,我将在其他服务中引用

@Injectable()
export class MapService {
    private isInit:boolean = false;
    private map: __esri.Map = null;
    private mapView: __esri.MapView = null;
    init(domElement: ElementRef) {
        if (this.isInit) return Promise.resolve(); // A guard? 
        loadModules(["esri/Map", "esri/views/MapView", "esri/widgets/ScaleBar"])
            .then(([Map, MapView, ScaleBar]) => {
                this.map = new Map();
                this.mapView = new MapView({
                    map: this.map,
                    container: domElement // This is where I need DOM element
                });
            })
            .catch(err => {
                // handle any errors
                console.error(err);
            })
            .then(() => {
                this.isInit = true;
            });
    }
}

这确实有效,我只是想知道,这是否是一种正确的方法。 我要求可以通过其他组件访问这些地图对象,添加/删除/更改地图图层,绘制/渲染几何图形和其他地图事物。

0 个答案:

没有答案