4

我只是在掌握 Angular (6) 框架,它的怪癖和功能。还有一件事,我需要,但看起来,它违背了 Angular 范式——一个服务,它需要对 DOM 节点的引用。

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

所以我有一个MapComponent类似于单例组件的组件——在应用程序中只包含一次。

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;
            });
    }
}

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

4

0 回答 0