[英]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,如果條件失敗,它會立即完成訂閱。
此外
observable<any>
必須是Observable<any>
function
關鍵字。 相反,您可以提及范圍標識符。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.