【问题标题】:Initialize BehaviourSubject with value from an Observable in an Angular template使用 Angular 模板中的 Observable 的值初始化 BehaviourSubject
【发布时间】:2021-01-21 11:46:55
【问题描述】:

我在 Angular 应用程序中经常使用以下模式。我有一个来自 RxJs BehaviourSubject 的 observable,它必须使用来自另一个 observable 的值进行初始化。我想在异步管道中使用它。我能做到这一点的唯一方法是这样的:

    ngOnInit() {
    this.notificationService
        .getNotificationForOperationId(`${this.operation.operationId}`)
        .subscribe((notification: Notification) => {
            this.activitiesExists = notification?.activities;
        });
}

然后我订阅对该变量的更改:

    subscription = this.notificationService.notificationUpdated$
    .subscribe(() => {
        this.activitiesExists = true;
    });

我在模板中使用变量:

 <ng-container *ngIf="activitiesExists">
   ...
</ng-container>

我宁愿将变量与异步管道一起使用,如下所示:

 <ng-container *ngIf="activitiesExists | async">
   ...
</ng-container>

但我不知道如何在 RxJs 语句中定义变量。我知道startWith() RxJs 运算符,但它只接受静态值而不是可观察值。

我想用这样的东西,但它似乎不存在:

    this.activitiesExists = this.notificationService.notificationUpdated$.pipe(
        startWith(this.notificationService.getNotificationForOperationId(this.operation.operationId))
    );

有没有办法实现这种行为?

【问题讨论】:

  • 不确定我是否理解您的问题。当您定义您的 behaviorSubject 时,您必须使用可以是任何类型甚至“任何”的默认值进行初始化。
  • 我相信 concating 你的 2 个 observables 可以工作
  • 更具声明性的方法会有所帮助吗?类似于此处介绍的内容:youtube.com/watch?v=e2KAn50QBBw 如果您可以构建一个简短的堆栈闪电战来演示该问题,我们可以进一步调查并提供更具体的回复。

标签: javascript angular rxjs


【解决方案1】:

也许更像是这样的声明性方法:

activitiesExists$ = this.notificationService
    .getNotificationForOperationId(`${this.operation.operationId}`)
    .pipe(
      map((notification: Notification) => notification?.activities)
    );

【讨论】:

  • 感谢您的意见。这样不包括第二个监听更新的 observable。
【解决方案2】:

以防万一有人感兴趣。看来我已经想通了:

        this.activitiesExist$ = this.notificationService
            .getNotificationForOperationId(this.operation.operationId)
            .pipe(
                switchMap((notification) =>
                    this.activitiesRecordingService.notificationUpdated$
                        .pipe(map((non) => non.operationId === this.operation.operationId))
                        .pipe(startWith(notification?.activities?.length > 0))
                )
            );

在第一步中,我获取当前值(操作通知)并立即 switchMap 以更新该值。 在那里,我使用“startWith”用第一个 observable 的结果初始化 observable。

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多