如何在valueChanges订阅中进行CombineLatest运算符

时间:2018-09-04 09:30:03

标签: angular reactive-programming rxjs6

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>

https://stackblitz.com/edit/angular-rs3d7a

1 个答案:

答案 0 :(得分:1)

错误提示为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将不会触发。 另外,逻辑是错误的,当其中两个都不为空时,您应该返回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