在我的 Angular 项目中,我使用这个组件来代表表单中的输入字段。目标是在用户更改输入字段的值时即时保存它:
export class SettingInputComponent implements OnInit, OnDestroy {
@Input() model: SettingInterface;
private subscriptions: Subscription = new Subscription();
private appDataService: AppDataServiceInterface<SettingInterface> =
new AppDataFactoryService<SettingInterface>().get(Setting);
private value$: BehaviorSubject<any> = new BehaviorSubject(this.model.value);
constructor() { }
ngOnInit(): void {
this.subscriptions.add(this.saveSetting().subscribe());
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
emitToSave(): void {
this.value$.next(this.model.value);
}
private saveSetting(): Observable<any> {
return this.value$.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(() => this.appDataService.save(this.model)
);
}
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<third-party-input
type="text"
[value]="model.value"
(change)="emitToSave()"
></third-party-input>
Run Code Online (Sandbox Code Playgroud)
问题是初始化saveSetting()可观察对象的组件何时会触发。我想避免这种行为,并且仅当用户更改模型的值属性时才触发。
如何避免在初始化时触发并仅在用户更改值时触发?
例子
const { of, iif, pipe , BehaviorSubject, Subscription, operators: { distinctUntilChanged, skip, switchMap, debounceTime } } = rxjs;
const value$ = new BehaviorSubject("initial");
const model = {}
const appDataService = {
save(model) {
return of(model);
}
}
const saveSetting = () => value$.pipe(
skip(1),
debounceTime(500),
distinctUntilChanged(),
switchMap((model) => appDataService.save(model))
);
saveSetting().subscribe(console.log);
setInterval(() => {
value$.next(Math.random().toString());
}, 2000);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8365 次 |
| 最近记录: |