如何在 valueChanges 订阅中执行 combineLatest 运算符
How to do combineLatest operator in valueChanges subscriptions
showDateCriteria = combineLatest(this.myForm.controls['name'].valueChanges, this.myForm.controls['age'].valueChanges, (name, age) => ({name, age}))
.subscribe(val => !(val.name==null ||val.age==null ));
我已经用 combineLatest 运算符和 showDateCriteria
尝试了这段代码
<div *ngIf="{{showDateCriteria | async}}">Show This</div>
即使满足特定条件,我也无法显示 <div>
如错误所述ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
。
您正在尝试异步传输订阅,这没有意义。
您应该通过管道传输流。
this.showDateCriteria =
combineLatest(
this.myForm.controls['name'].valueChanges,
this.myForm.controls['age'].valueChanges, (name, age) => ({
name,
age
}));
this.showDateCriteria.subscribe(val => !(val.name == null || val.age == null));
编辑:
你也应该startWith
,否则combineLatest
不会触发。
此外,逻辑错误,你应该 return boolean
true
当它们中的任何一个不为空时,就像这样:
this.showDateCriteria = combineLatest(
this.myForm.controls['name'].valueChanges.pipe(startWith(null)),
this.myForm.controls['age'].valueChanges.pipe(startWith(null)),
(name, age) => {
console.log(name);
return name || age;
});
https://stackblitz.com/edit/angular-g6vi6k?file=src%2Fapp%2Fapp.component.ts
showDateCriteria = combineLatest(this.myForm.controls['name'].valueChanges, this.myForm.controls['age'].valueChanges, (name, age) => ({name, age}))
.subscribe(val => !(val.name==null ||val.age==null ));
我已经用 combineLatest 运算符和 showDateCriteria
尝试了这段代码<div *ngIf="{{showDateCriteria | async}}">Show This</div>
即使满足特定条件,我也无法显示 <div>
如错误所述ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
。
您正在尝试异步传输订阅,这没有意义。
您应该通过管道传输流。
this.showDateCriteria =
combineLatest(
this.myForm.controls['name'].valueChanges,
this.myForm.controls['age'].valueChanges, (name, age) => ({
name,
age
}));
this.showDateCriteria.subscribe(val => !(val.name == null || val.age == null));
编辑:
你也应该startWith
,否则combineLatest
不会触发。
此外,逻辑错误,你应该 return boolean
true
当它们中的任何一个不为空时,就像这样:
this.showDateCriteria = combineLatest(
this.myForm.controls['name'].valueChanges.pipe(startWith(null)),
this.myForm.controls['age'].valueChanges.pipe(startWith(null)),
(name, age) => {
console.log(name);
return name || age;
});
https://stackblitz.com/edit/angular-g6vi6k?file=src%2Fapp%2Fapp.component.ts