[英]Return a regular array instead of Observable<T[]> in RxJS
可觀察的新手。 如何從此 function 返回常規數組而不是 observable?
removeRewards(userId: string): string[] {
return this.getUsedRewards(userId).pipe(
switchMap(rewards => rewards.filter(reward => reward.active)),
map(reward => reward.rewardId),
toArray()
);
}
getUsedRewards 返回一個 Observable。 我在不同的 function 中調用 removeRewards,只需要它返回 string[] 而不是 Observable<string[]>。
請指教,謝謝。
你必須結束 stream 然后使用toArray()
來實現你的目標你可以看到這個例子
“當間隔完成時,將間隔發出的值作為數組獲取”
// RxJS v6+
import { interval } from 'rxjs';
import { toArray, take } from 'rxjs/operators';
interval(100)
.pipe(take(10), toArray())
.subscribe(console.log);
// output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
所以你可以做類似的事情:
removeRewards(userId: string): string[] {
return this.getUsedRewards(userId).pipe(
switchMap(rewards => rewards.filter(reward => reward.active)),
map(reward => reward.rewardId),
take(1), // <-- ADD THIS LINE
toArray()
);
}
也可能的運算符是first()
如果它是一個 observable,你必須訂閱它以獲取 observable 發出的任何內容,然后以任何你想要的方式使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.