Angular / RxJs对一个observable的多个订阅

时间:2018-01-02 21:42:42

标签: angular rxjs angular-reactive-forms

我试图构建一个复杂的反应形式,我需要根据其他2个下拉值填充一个下拉列表。我发现当一个下拉列表发生变化时,如何从服务中获取值。但它不能用于2,因为第二个订阅取代了第一个订阅。我是否需要找到一种同步方式来填充第3个下拉列表?这就是我现在所拥有的:

constructor(private fb: FormBuilder, private defectsService: DefectsService) {
  this.searchForm = fb.group(this.searchCriteria);

  ...

  this.tradeParners$ = this.setupCascadingDropDown('community', (communityId: number) => {
    let tradePartnerData$ = this.defectsService
      .getTradePartners(communityId, this.searchForm.get('jobSite').value);
    this.tradeParnersSubscription = tradePartnerData$.do((x) => 
      console.log(`${x} trade partners`)
    ).subscribe();

    return tradePartnerData$;
  });

  this.tradeParners$ = this.setupCascadingDropDown('jobSite', (jobId: number) => {
    let tradePartnerData$ = this.defectsService
     .getTradePartners(this.searchForm.get('community').value, jobId);
    this.tradeParnersSubscription = tradePartnerData$.subscribe();
    return tradePartnerData$;
  });
}

private setupCascadingDropDown(controlName: string, getData): Observable<ISelectItem[]> {
  let control = this.searchForm.get(controlName);
  return control.valueChanges
    .do(test => console.debug(`${controlName}: ${test}`))
    .distinctUntilChanged()
    .switchMap(getData);
}

有什么方法可以在一个事件触发时订阅一个observable,并在另一个事件触发时替换它?

更新

这里是填充使用observable的下拉列表的代码。

<label class="col-sm-2 col-md-2 control-label">Trade Partner:</label>
<div class="col-sm-3 col-md-3">
  <select class="hbp-defect-select" formControlName="tradePartner">
    <option value="-1">- All -</option>
    <option *ngFor="let tp of tradePartners$ | async" [ngValue]="tp.value">{{ tp.text }}</option>
  </select>
</div>

1 个答案:

答案 0 :(得分:0)

这确实很复杂,但我想我已经掌握了它。

const tradeParnersFromCommunity$ = this.setupCascadingDropDown('community', (communityId: number) => {
  let tradePartnerData$ = this.defectsService
    .getTradePartners(communityId, this.searchForm.get('jobSite').value);
  this.tradeParnersSubscription = tradePartnerData$.do((x) => 
    console.log(`${x} trade partners`)
  ).subscribe();

  return tradePartnerDataFromJobsite$;
});

this.tradeParnersFromJobsite$ = this.setupCascadingDropDown('jobSite', (jobId: number) => {
  let tradePartnerData$ = this.defectsService
   .getTradePartners(this.searchForm.get('community').value, jobId);
  this.tradeParnersSubscription = tradePartnerData$.subscribe();
  return tradePartnerData$;
});

this.tradeParners$ = tradeParnersFromCommunity$.merge(tradeParnersFromJobsite$);

您可能也想在那里进行排序?