在我的 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)
);
}
}
HTML:
<third-party-input
type="text"
[value]="model.value"
(change)="emitToSave()"
></third-party-input>
问题是当组件初始化 saveSetting()
observable 时将会触发。我想避免这种行为,并且仅当用户更改模型的 value 属性时才触发。
如何避免在初始化时触发以及仅在用户更改值时触发?
最佳答案
I think skip method would help here
示例
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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>
关于angular - 如何使用 RxJS 跳过可观察值的第一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69393781/