1

在 Angular 中,如何将复选框绑定到 rxjs BehaviorSubject?我想更改复选框以触发执行一些操作的订阅。目前我有以下黑客攻击:

openSessionsOnly$ = new BehaviorSubject(false);

这是在我的模板中:

<input type="checkbox" #openSessionsOnly [checked]="openSessionsOnly$.value" (change)="openSessionsOnly$.next(openSessionsOnly.checked)"/>

虽然它有效,但我觉得我做错了什么。我尝试使用[(ngModel)],但它似乎不适用于可观察对象。我是否需要像我已经拥有的那样使用单独的属性和事件绑定?

4

2 回答 2

4

使用 TypeScript 属性很容易完成:

private openSessionsOnly$ = new BehaviorSubject(false);

get openSessionsOnly(): boolean {
  return this.openSessionsOnly$.value;
}
set openSessionsOnly(v: boolean) {
  this.openSessionsOnly$.next(v);
}

现在您可以在模板中绑定事件或直接使用ngModel

<!-- you will need a name if inside a form -->
<input type="checkbox" [(ngModel)]="openSessionsOnly" />

请注意,您无法保证 next 将被调用的最少次数,因此您可能希望distinctUntilChanged在可观察管道中抛出 a 。

于 2020-03-26T21:38:01.953 回答
3

您是否考虑过使用反应式表单控件?无需重新发明轮子,开箱即用的角度支持。您可以拥有一个反应式表单组,它为您的复选框提供一个反应式表单控件,并且 Angular 将为您处理可观察到的值更改,您需要做的就是管道到可观察的反应式表单提供,然后使用基于您的 switch 运算符需要,例如switchMap(将取消以前的订阅)以防发出新值或耗尽 Map(将阻止新订阅,直到当前订阅完成)

例子

<form [formGroup]='formGroup'> 
<input type='checkbox' formControlName='checkboxControlName' value='true' />
</form>  

component
  formGroup = new FormGroup({
    checkboxControlName: new FormControl(false),
  });

ngOnInit(){
//Filter is in case you need to make sure the checkbox is checked. 
this.formGroup.get('checkboxControlName').valueChanges.pipe(
     filter(val) => val === true), 
     switchMap(val => add your new subscription here));
}

进一步阅读

于 2020-03-27T08:23:27.433 回答