【发布时间】:2020-12-07 13:06:11
【问题描述】:
角度:11.0.2 (显示我的问题的简化示例)
我在ngIf 模板中使用async 管道时遇到了一些问题(我的数据没有很好地刷新)。我写了一个简单的例子来暴露我的问题。
重现步骤:
- 点击
add多次 - 点击
toggle -
data$ | async显示defaultValue而不是myArray值(非预期) - 点击
add -
data$ | async已刷新并显示myArray值(预期) - 点击2次
toggle -
data$ | async再次显示defaultValue(不是预期的)
看起来 ngIf 将 data$ 初始值存储在第一个 ngOnInit 上。为什么{{data$ | async | json}} 在切换ngIf 块时返回myArray 的默认值(即使myArray 已更改)。
如何使用rxjs 和ngIf 处理这种情况?
模板:
<button (click)="add()">+ add</button>
<button (click)="sub()">- sub</button>
<button (click)="toggle()">toggle</button>
myArray={{myArray.value | json}}
length={{myArray.length}}
<div *ngIf="showMe">
Inside ngIf:<br>
data={{data$ | async | json}}<br>
myArray={{myArray.value | json}}
</div>
组件:
import { Component, OnInit,ChangeDetectorRef } from "@angular/core";
import { FormArray, FormBuilder } from "@angular/forms";
import { combineLatest, Observable, of } from "rxjs";
import { filter, map, startWith, tap } from 'rxjs/operators';
@Component({
selector: "my-app",
templateUrl: "src/app.component.html"
})
export class AppComponent implements OnInit{
showMe = false;
form: FormGroup;
x: number = 0;
data$: Observable<any>;
constructor(
private fb: FormBuilder,
private cd: ChangeDetectorRef
) {}
ngOnInit() {
this.form = this.fb.group({
myArray: this.fb.array(['defaultValue'])
}) ;
this.data$ = this.myArray.valueChanges.pipe(startWith(this.myArray.value));
}
add() {
this.myArray.push(this.fb.control(this.x++));
}
sub() {
this.myArray.removeAt(this.myArray.length - 1);
}
toggle() {
this.showMe = !this.showMe;
}
get myArray(): FormArray {
return this.form.get('myArray') as FormArray;
}
}
【问题讨论】:
标签: javascript angular typescript