[英]Angular 2: Update FormControl validator after valueChanges
[英]RxJS / Angular: Capture valueChanges of FormControl before subscribing
我嘗試從FormControls.valueChanges
observable 發出的值創建一個 observable。 observable 在ngOnInit
方法中創建如下:
ngOnInit(): void {
this.myObservable$ = combineLatest([
this.formControl1.valueChanges,
this.formControl2.valueChanges
]).pipe(
map(([v1, v2]) => parseInt(v1, 10) + parseInt(v2, 10))
);
this.isLoading = true;
this.loadData().subscribe({
next: result => {
this.formControl1.setValue(result[0]);
this.formControl2.setValue(result[1]);
this.isLoading = false;
},
});
}
在isLoading
設置為 false 后訂閱 observable:
<div *ngIf="!isLoading">{{ myObservable$ | async }}</div>
因此,在這種情況下, myObservable$
只會在formControl1
和formControl2
手動更改后開始發出值,因為valueChanges
的第一次發出發生在訂閱此 observable 之前。
您可以為此編寫一個非常詳細的解決方案:
this.myObservable$ = defer(() => combineLatest([
this.formControl1.valueChanges.pipe(startWith(this.formControl1.value)),
this.formControl2.valueChanges.pipe(startWith(this.formControl2.value))
])).pipe(
map(([v1, v2]) => parseInt(v1, 10) + parseInt(v2, 10))
);
有沒有更漂亮的解決方案?
( https://angular-ivy-n1gwvk.stackblitz.io是 StackBlitz 的一個最小示例)
您可以在模板中執行以下操作。 也是冗長的,但這是另一種方式。 否則startWith
是解決此問題的正確方法:
<ng-container *ngIf="{ value: (myObservable$ | async) } as my">
<div *ngIf="!isLoading">{{ my.value }}</div>
</ng-container>
另一種方法是訂閱它並使用shareReplay
:
isLoading: true;
readonly destroy$ = new Subject<void>();
ngOnInit(): void {
this.myObservable$ = combineLatest([
this.formControl1.valueChanges,
this.formControl2.valueChanges
]).pipe(
map(([v1, v2]) => parseInt(v1, 10) + parseInt(v2, 10)),
shareReplay(1),
takeUntil(this.destroy$)
);
this.myObservable$.subscribe();
this.loadData().subscribe({
next: result => {
this.formControl1.setValue(result[0]);
this.formControl2.setValue(result[1]);
this.isLoading = false;
},
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
我能想到的唯一方法是提取一些輔助沙子嘗試取出一些重復。
// Helpers
const getControlValueStream = (({ control, valueChanges }): FormControl) => valueChanges.pipe(startWith(value));
const sumNumbers = (numbers: number[]) => numbers.reduce((a, b) => a + b, 0);
// Component
const controls = [this.formControl1, this.formControl2];
const valueStreams = controls.map(getControlValueStream);
combineLatest(...valueStreams).pipe(
map(values => values.map(value => parseInt(value, 10))),
map(sumNumbers),
);
但是,您或您的團隊可能會發現這不太可讀,這是一個公平的觀點 - 漂亮應該與可維護性相平衡。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.