簡體   English   中英

Angular, 2 科目, combineLatest 不工作

[英]Angular, 2 subjects, combineLatest not working

  $query: Subject<string> = new Subject();
  $order: Subject<string> = new Subject();

  constructor() {
    combineLatest([this.$query, this.$order]).pipe(
      debounceTime(300),
      startWith([null, 'Oldest'])
    ).subscribe(([query, order]) => {
      console.log('query', query);
      console.log('order', order);
    });  
  }

日志只顯示一次,在我嘗試調用$query.next('sthg')之后,它不起作用。

有人知道為什么嗎? 如果$query$order獲得新值,我想記錄這些值。 最新的組合不能與主題一起使用嗎?

所有源 Observable 都需要至少發出一次,因此您可以使用它:

combineLatest([
  this.$query.pipe(startWith(null)),
  this.$order.pipe(startWith("Oldest")),
]).pipe(
  debounceTime(300),
)
.subscribe(...);

這樣,您將獲得您期望的第一個發射,然后它應該在每次更改時發射。

根據文檔,為了使其工作,兩個可觀察對象必須發出至少一個值。 你可以嘗試這樣的事情:

  combineLatest([this.$query, this.$order.pipe(startWith("Oldest")]).pipe(
    debounceTime(300),
  ).subscribe(([query, order]) => {
    console.log('query', query);
    console.log('order', order);
  });

然后,當您調用$query.next('sthg')時,您應該會看到控制台日志。

來自combineLatest (learnrxjs.io)

請注意,在每個 observable 發出至少一個值之前, combineLatest 不會發出初始值 這與 withLatestFrom 的行為相同,並且可能是一個陷阱,因為不會有 output 並且沒有錯誤,但是您的一個(或多個)內部可觀察對象可能無法按預期運行,或者訂閱延遲。

我個人使用BehaviorSubject作為源並添加filter pipe 以逃避不需要的組合:

combineLatest([this.obs1$, this.obs2$, this.obs3$])
    .pipe(
      filter((result) => {
        let valueObs1 = result[0];
        let valueObs2 = result[1];
        let valueObs3 = result[2];

        if (logic tgo escape) 
             return false;

        return true;
      })
    )
    .subscribe(
      (result) => console.log(result),
      (error) => console.log(error)
    );

暫無
暫無

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

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