我有一個Observable<FormGroup>有幾個布林值FormControl
readonly someForm$ = model$.pipe(map((model: Model) => {
return new FormGroup({
foo: new FormControl(model.getFoo()),
bar: new FormControl(model.getBar()),
});
}));
我想創建一個可觀察的,如果任何FormControl值是true. 我嘗試了以下
readonly result$ = someForm$.pipe(switchMap(
form => form.valueChanges.pipe(
map(changes => changes.foo || changes.bar),
startWith(() => form.value['foo'] || form.value['bar'])
)
));
雖然總是在測驗期間result$解決。true什么是創建本質上是 observable 的正確方法foo || bar?
最小的例子:https ://stackblitz.com/edit/angular-material-bvy7bj
uj5u.com熱心網友回復:
有幾個問題:
您
result$在組件和$result模板中都有。startWith()不接受函式,它必須是您的用例中的值。您進行了兩次訂閱,
someForm$這會創建兩個不相關的FormGroup實體。您需要shareReplay(1)在someForm$.
您更新的演示:https ://stackblitz.com/edit/angular-material-xpqmcs?file=app/app.component.ts
uj5u.com熱心網友回復:
使用filter運算子過濾掉虛假值
const result$ = someForm$.pipe(
switchMap((form) =>
form.valueChanges.pipe(
filter((changes) => changes.foo || changes.bar),
map((changes) => changes.foo || changes.bar)
)
)
);
我創建了模擬表單和模擬用戶事件
import { BehaviorSubject, of } from 'rxjs';
import { filter, map, startWith, switchMap } from 'rxjs/operators';
const someForm$ = of({ // custom Observable form
valueChanges: new BehaviorSubject({
foo: false,
bar: false,
}),
value: {
foo: false,
bar: false,
},
});
const result$ = someForm$.pipe(
switchMap((form) =>
form.valueChanges.pipe(
filter((changes) => changes.foo || changes.bar), // filtering falsey values
map((changes) => changes.foo || changes.bar) // map to true
)
)
);
result$.subscribe((data) => {
console.log(data);
});
someForm$.subscribe((data) => {
data.valueChanges.next({ foo: false, bar: true }); // custom user event
data.valueChanges.next({ foo: false, bar: false }); // custom user event
data.valueChanges.next({ foo: true, bar: false }); // custom user event
});
演示:
https://stackblitz.com/edit/typescript-tfqjms?file=index.ts&devtoolsheight=100
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449565.html
上一篇:我可以宣告陣列文字的型別嗎?
