应用
到目前为止,我已将SearchComponent
放在MapViewComponent
模板中,以便我可以使用SearchComponent
将其传递给@Inject(forwardRef(() => MapViewComponent))
。但是由于搜索组件应该显示在布局/ 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()
之前被调用。
答案 0 :(得分:5)
您应该使用Subject
(BehaviorSubject
或ReplaySubject
)。 Subject
将充当生产者和消费者。它的消费者可以订阅它,就像一个可观察的。生产者可以使用它向消费者发送消息。例如
import { ReplaySubject } from 'rxjs/ReplaySubject'
@Injectable()
export class MapService {
private _currentMapView = new ReplaySubject<MayView>(1);
setCurrentView(mv: MapView){
this._currentView.next(mv);
}
get currentMapView$() {
return this._currentMapView.asObservable();
}
}
订阅者只需要抄写
import { Subscription } from 'rxjs/Subscription';
export class SearchComponent {
sub: Subscription;
view: MapView;
constructor(private elRef:ElementRef, private mapService: MapService ) {
}
ngOnInit() {
this.sub = this.mapService.currentMapView$.subscribe(view => {
this.view = view;
})
}
ngOnDestroy() {
if (this.sub) {
this.sub.unsubscribe();
}
}
}
MapViewComponent
只需拨打setCurrentView
即可在订阅时自动处理
另见:
Subject
/ BehaviorSubject
/ ReplaySubject