角度绑定复选框到BehaviorSubject

Bri*_*ian 5 rxjs angular

在 Angular 中,如何将复选框绑定到 rxjs BehaviorSubject?我希望更改复选框以触发执行一些操作的订阅。目前我已经破解了以下内容:

openSessionsOnly$ = new BehaviorSubject(false);
Run Code Online (Sandbox Code Playgroud)

这是我的模板中的:

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

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

A. *_*esa 10

使用 TypeScript 属性可以轻松完成此操作:

private openSessionsOnly$ = new BehaviorSubject(false);

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

Run Code Online (Sandbox Code Playgroud)

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

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

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


Mun*_*zer 5

Did you consider using reactive form controls ? No need to reinvent the wheel, angular support this out of the box. you can have a reactive form group, which has a reactive form control for your checkbox, and angular will handle value changes observable for you, all you need to do is pipe to the observable reactive forms provide and then use a switch operator based on your need, for example switchMap (will cancel previous subscription) in case a new value was emitted or exhaustMap (will prevent new subscription until current one completes)

example

<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));
}
Run Code Online (Sandbox Code Playgroud)

Further Read