【发布时间】:2016-11-08 00:18:00
【问题描述】:
应用
- 地图视图组件
- SearchComponent(需要 MapViewComponent 的对象)
- 地图服务
到目前为止,我将SearchComponent 放在MapViewComponents 模板中,这样我就可以使用@Inject(forwardRef(() => MapViewComponent)) 将它传递给SearchComponent。但由于搜索组件应该显示在布局/HTML DOM 中的其他位置,我想我必须使用服务将 MapViewComponent 传递给搜索。
MapViewComponent.ts:
export class MapViewComponent {
@Output() onMapViewCreated = new EventEmitter();
private _view: any = null;
constructor(private mapService: MapService, private elRef: ElementRef) {
}
ngOnInit() {
this._view = new MapView({
container: this.elRef.nativeElement.firstChild,
map: this._mapService.map,
center: [5.44, 36.947974],
rotation: 0,
autoResize: true
})
this._view.then((view) => {
this.onMapViewCreated.next(view);
this._mapService.setView(view);
});
SearchComponent.ts:
export class SearchComponent {
constructor(private elRef:ElementRef, private mapService: MapService ) {
var view = mapService.getView();
}
}
MapService.ts:
@Injectable()
export class MapService {
public setView(mv: MapView){
this.view = mv; // what do I have to do here..?
}
public getView(){
return this.view; // .. and here?
}
}
它显然不会那样工作,因为getView() 可能会在setView() 之前被调用。
【问题讨论】:
-
您应该将
Observable<MapView>或Promise<MapView>存储为视图,然后您将在getter 中返回Observable/promise,这允许您执行getView().then(your function...)并解决您的promise/emit设置视图后,在您的 observable 中。编辑:什么是 MapView?
标签: javascript angular typescript