【发布时间】: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