簡體   English   中英

如何將可觀察值傳遞給rxjs主題?

[英]How do I emit the value of an observable to an rxjs Subject?

我想從Angular服務提供rxjs Subject ,以便能夠通過調用服務上的方法來發出值(通過next )。 我希望它發出的值之一是Angular HttpClient get調用的結果。 我似乎無法正確解決。 我想知道為什么以下結果導致未調用訂閱處理程序:

-視圖

export default abstract class TileView implements OnInit {
  constructor (private configService : ConfigService) {}
  ngOnInit () {
    this.configService.fetch(this.type()).subscribe( res => {
      console.log(res)
    }); 
  }
}

-服務

export class ConfigService {
  public subject = new AsyncSubject();

  constructor (private http : HttpClient) {}

  fetch (type) {
    this.http.get(
      api.host + api.base + interpolate(api.config, { type }) + "/"
    ).subscribe( res => {
      this.subject.next(res);
    });

    return this.subject;
  }
}

有什么方法可以返回主題,也可以通過單個方法調用觸發http調用嗎? 這很奇怪,因為返回了主題,注冊了訂閱者,完成了http調用,並調用了this.subject.next(res) ,但是訂閱處理程序甚至沒有運行。

Pierre,發生這種情況的原因是因為AsyncSubject僅在可觀察對象完成時 (由Subject.prototype.complete()確定Subject.prototype.complete() 才發出最后一個值

在您的情況下,您可能希望使用BehaviorSubject來為訂閱者(無論完成情況)發出流中的最后一個值:

AsyncSubject發出源Observable發出的最后一個值(並且僅發出最后一個值),並且僅在該源Observable完成之后發出。 (如果源Observable不發出任何值,則AsyncSubject也將完成而不會發出任何值。)

主題文件

更新:

如果由於初始值傳播而不願意使用BehaviorBehavior,請使用ReplaySubject(1)。

完成可觀察的,它將起作用

fetch (type) {
    this.http.get(
      api.host + api.base + interpolate(api.config, { type }) + "/"
    ).subscribe( res => {
      this.subject.next(res);
      this.subject.complete();
    });

    return this.subject;
  }

另一種方法是使用BehaviourSubject,在這種情況下,您需要處理null檢查,因為BehaviourSubject需要默認值

public behaviourSub = new BehaviorSubject(null);

this.configService.fetch(this.type()).subscribe( res => {
    if (res !== null) {
      // actual value emitted
    }
});

AsyncObservable的特殊性之一是他在發送信息之前等待“ complete() ”完成

由於AsyncSubject擴展了Observable,所以沒有必要,但是我建議您使用“ return this.subject.asObservable() ”,它是“ Subject”對象的一部分。 由於您需要在其他類型的主題上使用它,因此,例如,如果您通過BehaviourSubject更改主題的類型,則無需更改代碼;)

訂閱視圖中的“主題”以免獲取。 並且也無需從您的服務中退還該主題。

視圖:

export default abstract class TileView implements OnInit {
  constructor (private configService : ConfigService) {}
  ngOnInit () {
    this.configService.subjectChanged(this.type()).subscribe( res => {
      console.log(res)
    }); 
  }
}

服務:導出類ConfigService {

  public subjectChanged = new Subject();

  constructor (private http : HttpClient) {}

  fetch (type) {
    this.http.get(
      api.host + api.base + interpolate(api.config, { type }) + "/"
    ).subscribe( res => {
      this.subjectChanged.next(res);
    });
  }
}

暫無
暫無

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

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