Angular2 - Waiting for service variable to be initialized

前端 未结 1 1366
天命终不由人
天命终不由人 2021-01-25 08:12

Application

  • MapViewComponent
  • SearchComponent (requires an object of the MapViewComponent)
  • MapService

So far, I placed the Se

相关标签:
1条回答
  • 2021-01-25 09:08

    You should use a Subject (either BehaviorSubject or ReplaySubject). The Subject will act as both a producer and consumer. The consumer of it can subscribe to it, just like an observable. And the producer can use it to emit messages to consumers. For example

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

    The subscriber just needs to suscribe

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

    The MapViewComponent just needs to call the setCurrentView, and it will be handled by the subscribers automatically when it's sent

    See Also:

    • This post for a brief description about difference between Subject/BehaviorSubject/ReplaySubject
    0 讨论(0)
提交回复
热议问题