简体   繁体   English

返回一个常规数组而不是 Observable<t[]> 在 RxJS</t[]>

[英]Return a regular array instead of Observable<T[]> in RxJS

New to observables.可观察的新手。 How do I return a regular array from this function instead of an observable?如何从此 function 返回常规数组而不是 observable?

removeRewards(userId: string): string[] {
  return this.getUsedRewards(userId).pipe(
  switchMap(rewards => rewards.filter(reward => reward.active)),
  map(reward => reward.rewardId),
  toArray()
  );
}

getUsedRewards returns an Observable. getUsedRewards 返回一个 Observable。 I'm calling removeRewards in a different function and just need this to return string[] instead of Observable<string[]>.我在不同的 function 中调用 removeRewards,只需要它返回 string[] 而不是 Observable<string[]>。

Please advise, thanks.请指教,谢谢。

You must END the stream and then use toArray() to achieve your goal You can see this example你必须结束 stream 然后使用toArray()来实现你的目标你可以看到这个例子

"get values emitted by interval as an array when interval completes " “当间隔完成时,将间隔发出的值作为数组获取”

// 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]

So u can do something like:所以你可以做类似的事情:

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()
  );
}

Also possible operator is first()也可能的运算符是first()

If it is an observable, you have to subscribe it to get whatever observable emits and then use it in whatever way you want.如果它是一个 observable,你必须订阅它以获取 observable 发出的任何内容,然后以任何你想要的方式使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM