需要在UI中显示一个倒计时计数器10秒,而等待下面的可观察emits . 如果低于10秒可观察不emits 其超时.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)             
            }
        });

我有一个不同的计数器功能,但想知道它是否可以棒状,以便在等待观察emits 计数器时可以在UI中显示.

推荐答案

您可以使用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$是一个可观察流,它发出一个具有countdownauthenticated属性的对象,允许你在模板中显示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

Angular相关问答推荐

升级到angular 17并转换为独立的加载器拦截器后,

使用注入的主机组件进行指令测试

未触发HTTP拦截器

带迭代的Angular 内容投影

MAT-复选框更改事件未在onSubscriberCheck函数中返回选中的值

从canActivate创建时,Angular material 对话框不接收MAT_DIALOG_DATA

从Angular 前端访问ASP.NET Core 8 Web API时出现CORS错误

元素上的Angular 管道链接不起作用

如何让 ag-Grid 事件读取私有方法?

无法在单个元素上多次监听同一个事件

ng 生成组件不会创建 ngOnInit 和构造函数

等待多个promises完成

Angular 2:无法绑定到 x,因为它不是已知的本机属性

ERROR 错误:StaticInjectorError(AppModule)[UserformService -> HttpClient]:

如何在 Angular 2 中创建可重用的动画

将 Angular 5 升级到 6 时,我得到不兼容的对等依赖(使用 ng update @angular/core)

Angular - 是否有 HostListener-Events 列表?

angular4的所见即所得编辑器

Angular 4中的md-select中的onselected事件

Firestore 从集合中获取文档 ID