有没有一种方法可以使用 timeout() 运算符创建计数器,用于使可观察对象超时?

问题描述 投票:0回答:1

需要在 UI 中显示倒数计数器 10 秒,同时等待下面的可观察值发出。 如果低于 observable 在 10 秒内没有发出,则超时。 UI计数器也可以在下面的代码中加入吗?

 this.authSubscription =     onauthReceived$.pipe(timeout({ first: 10 * 1000 })).subscribe({
            next: () => {
                console.log('do something)
            },
            error: err => {
                console.log('timed out before 7 seconds: ', err);
            },
            complete: () => {
                
                             console.log('complete)             
            }
        });

我有一个不同的计数器功能,但想知道它是否可以被组合,以便在等待可观察到的发出计数器时可以在 UI 中显示。

angular rxjs
1个回答
0
投票

您可以使用

combineLatest
运算符组合两个或多个流:

@Component(...)
export class App {
  authenticated$ = new Subject<string>();

  viewModel$ = combineLatest({
    authenticated: this.authenticated$.pipe(
      timeout(10 * 1000),
      startWith(null)
    ),
    countdown: timer(0, 1000).pipe(
      map((count) => 10 - count),
      takeUntil(this.authenticated$)
    ),
  }).pipe(
    catchError(() =>
      of({
        authenticated: 'you were too late!',
        countdown: 0,
      })
    )
  );
}

在我的示例中,

viewModel$
是一个可观察流,它发出一个具有
countdown
authenticated
属性的对象,允许您在模板中显示
viewModel.countdown
的值:

<button (click)="authenticated$.next('authenticated!')">authenticate</button>
<pre>{{viewModel$ | async | json}}</pre>

这是一个工作示例:https://stackblitz.com/edit/stackblitz-starters-jwyazf?file=src%2Fmain.ts

© www.soinside.com 2019 - 2024. All rights reserved.