Angular2 - 等待服务变量初始化

时间:2016-11-07 15:51:32

标签: javascript angular typescript

应用

  • MapViewComponent
  • SearchComponent(需要MapViewComponent的对象)
  • 的MapService

到目前为止,我已将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()之前被调用。

1 个答案:

答案 0 :(得分:5)

您应该使用SubjectBehaviorSubjectReplaySubject)。 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即可在订阅时自动处理

另见:

  • This post有关Subject / BehaviorSubject / ReplaySubject
  • 之间差异的简要说明