簡體   English   中英

我需要分享Angular2可觀察對象

[英]Angular2 observables do I need to share

我有用於搜索的表單輸入。 當用戶在搜索輸入中輸入內容時,我需要調用2個單獨的api。 這是我要實現的目標:

myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;

ngOnInit(){
    this.listOne = this.myInput.valueChanges
                     .debounceTime(500)
                     .distinctUntilChanged()
                     .switchMap(myInput => this._service.getListOne(myInput));

    this.listTwo = this.myInput.valueChanges
                     .debounceTime(500)
                     .distinctUntilChanged()
                     .switchMap(myInput => this._service.getListTwo(myInput));
}

所以我的問題是,我該如何訂閱valueChanges並調用2個不同的api來填充2個不同的數組? 使用上面的代碼,它可以很好地用於初始搜索,但是當我更改搜索文本時,僅調用getListTwo。

每當一個源有多個訂閱者,並且您希望這些訂閱者從該源讀取相同的值時(換句話說,您要將源值多播到多個訂閱者),則應該share

這意味着: sharedSource = this.myInput.valueChanges.debounceTime(500).distinctUntilChanged().share() ,例如:

myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;

ngOnInit(){
    this.listOne = sharedSource
                     .switchMap(myInput => this._service.getListOne(myInput));

    this.listTwo = sharedSource
                     .switchMap(myInput => this._service.getListTwo(myInput));
}

您可以在此處查看多播與冷流的詳細說明。

ngOnInit(){
  input$ = this.myInput.valueChanges.debounceTime(500)
                         .distinctUntilChanged()
                         .share();

  this.listOne = input$.switchMap(myInput => this._service.getListOne(myInput));
  this.listTwo = input$.switchMap(myInput => this._service.getListTwo(myInput));

  //store subscriptions
  this.subs$.push(input$,this.listOne,this.listTwo);
}

請記住退訂以避免內存泄漏:

ngOnDestroy(){
    this.subs$.forEach(s => s.unsubscribe());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM