簡體   English   中英

Rxjs combineLatest 確實在訂閱中返回了 observable

[英]Rxjs combineLatest does returning the observable with in the suscribe

在我需要根據 userid 接聽電話后,我正在嘗試獲取 Userid 和 serviceId,這里的 serviceId 問題是它沒有將 observable 返回給 ts。

服務.ts

function getData():observable<any>{
   combineLatest([
      this.activeSellService.getActiveSellServiceId(),
      this.authService.getUserId(),
    ]).subscribe(([serviceId, userId]) => {
      if (serviceId&& userId) {
        const Url =
          'users/' +
          `${userId}` +
          '/services/' +
          `${serviceId}` +
          '?value=test
        return this.http.get<any>(this.endPoint.getUrl(encodeURI(Url)));
      }
    })
}

組件.ts:

 this.service.getData().subscribe(data=>{console.log(data));

即使它沒有在控制台中打印數據,因為服務沒有返回可觀察的。 請幫我解決這個問題。 否則我們可以在 rxjs 中使用不同的解決方案嗎?

試試這個

function getData():observable<any>{
   return combineLatest(
      this.activeSellService.getActiveSellServiceId(),
      this.authService.getUserId(),
    ).pipe(mergeMap([serviceId, userId]) => {
      if (serviceId && userId) {
        const Url =
          'users/' +
          `${userId}` +
          '/services/' +
          `${serviceId}` +
          '?value=test
        return this.http.get<any>(this.endPoint.getUrl(encodeURI(Url)));
      }
    })
}

請注意 combinelatest 的參數,並且 getData 中沒有訂閱

例如在堆棧閃電戰中:

https://stackblitz.com/edit/angular-rxjs-combinelatest-hjyfa6?file=src/app/app.component.ts

您需要使用像switchMap這樣的高階映射運算符來從一個可觀察switchMap映射到另一個。 此外, subscribe()函數只接受回調並且只返回包含訂閱的Subscription對象。

如果if條件失敗,您也不會返回任何內容。 你可以返回一個像 RxJS 常量EMPTY這樣的 observable,如果條件失敗,它會立即完成訂閱。

此外

  1. observable<any>必須是Observable<any>
  2. 您還沒有從函數中返回。
  3. Typescript 中不需要function關鍵字。 相反,您可以提及范圍標識符。
  4. 您將字符串連接與模板文字混合使用。 雖然它在語法上沒有錯誤,但我認為最好堅持使用其中之一。
  5. 從函數的上下文中猜測,我相信您希望提出一次請求並完成它。 而不是combineLatest提供的數據流。 在這種情況下,您可以改用forkJoin 但是請注意, forkJoin僅在其所有源完成時才發出。

嘗試以下

import { Observable, forkJoin, EMPTY } from 'rxjs';
import { switchMap } from 'rxjs/operators';

public getData(): Observable<any> {
  return forkJoin([
    this.activeSellService.getActiveSellServiceId(),
    this.authService.getUserId(),
  ]).pipe(
    switchMap(([serviceId, userId]) => {
      if (!!serviceId && !!userId) {
        const Url = `users/${userId}/services/${serviceId}?value=test`;
        return this.http.get<any>(this.endPoint.getUrl(encodeURI(Url)));
      } else {
        return EMPTY;
      }
    })
  );
}

暫無
暫無

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

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