微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-Angular2-等待服务变量被初始化

应用

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

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

解决方法:

您应该使用Subject(BehaviorSubject或ReplaySubject).主题将同时充当生产者和消费者.它的消费者可以订阅它,就像观察到的一样.生产者可以使用它向消费者发送消息.例如

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简要说明主题/行为主题/重放主题间的区别

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐