简体   繁体   English

如何解决在 Rxjs 中发送到 Subject 参数的 promise?

[英]How to resolve a promise that sent to Subject parameters in Rxjs?

I pass a Promise to Subject as parameter:我将Promise作为参数传递给Subject

const work = new Subject<{ id: number; dialogRef: Promise<typeof Dialog> }>();

And I want to use the instance inside the promise later:我想稍后使用promise内部的实例:

...
exhaustMap(({ id, dialogRef }) =>
  http.get({ id }).pipe(tap(() => dialogRef.close()))
)
...

But the problem is dialogRef is a Promise , I need to resolve it before I use instance function ( close() ).但问题是dialogRefPromise ,我需要在使用实例 function ( close() )之前解决它。

The one way I was be able to do that is using async await , but this solution is not good for me.我能够做到这一点的一种方法是使用async await ,但这个解决方案对我不利。 because I want to do it using "rxjs" way.因为我想用“rxjs”的方式来做。

I looking for operator or function that can resolve this promise and pass it to exhaustMap operator.我正在寻找可以解决此 promise 并将其传递给exhaustMap操作员的操作员或 function。 something like that:类似的东西:

 resolve(({ dialogRef }) => dialogRef),
 exhaustMap(({ id, dialogRef }) => //<-- dialogRef is NOT promise. it's instance
      http.get({ id }).pipe(tap(() => dialogRef.close()))
 )

Can I do it with rxjs?我可以用 rxjs 做吗?

stackblitz 堆栈闪电战

import { of, Subject } from 'rxjs';
import { exhaustMap, tap } from 'rxjs/operators';
console.clear();

const http = {
  get: ({ id }) => of(`data: ${id}`),
};

const Dialog = {
  close: () => {
    console.log('in close!');
  },
};

const work = new Subject<{ id: number; dialogRef: Promise<typeof Dialog> }>();

work
  .pipe(
    exhaustMap(({ id, dialogRef }) =>
      http.get({ id }).pipe(tap(async () => (await dialogRef).close()))
    )
  )
  .subscribe((r) => {
    console.log({ r });
  });

work.next({ id: 1, dialogRef: Promise.resolve(Dialog) });

like this?像这样? https://stackblitz.com/edit/rxjs-geomjb https://stackblitz.com/edit/rxjs-geomjb

work.pipe(
    concatMap(({ id, dialogRef }) => forkJoin({ id: of(id), dialogRef })),
    exhaustMap(({ id, dialogRef }) => http.get({ id }).pipe(tap(() => dialogRef.close())))
).subscribe(...);

use concat like this:像这样使用concat

work.pipe(
  exhaustMap(({id, dialogRef}) => concat(http.get(id), dialogRef.close()))
).subscribe()

If you want to run dialogRef.close after http.get , just add defer for it:如果你想在dialogRef.close之后运行http.get ,只需为其添加defer

work.pipe(
  exhaustMap(({id, dialogRef}) => concat(
    http.get(id),
    defer(() => dialogRef.close())
  ))
).subscribe()

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

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