angular - 如何使用 RxJS 跳过 observable 的第一个值?
问题描述
在我的 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 属性时触发。
如何避免在初始化时触发并仅在用户更改值时触发?
解决方案
例子
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>
推荐阅读
- python - im7 图像文件到 openCV
- angular - 如何将点击数据传递到模态的背景以在 onDidDismiss 回调函数中接收?离子 3 角 6
- django - 付款确认后如何在django用户中处理?
- java - 是否有在 Eclipse 中使用 Jsoup 修复或绕过 HTTPStatusException 403 错误的解决方案?
- java - 我使用 Java 中的 inteliJ 在编辑器上编写的任何内容都会出现错误。(可能是 IDE 问题?)
- android - 可以使用calculateroute.json在android sdk中路由
- c# - 当动作接受参数时,控制器动作被调用两次。由“快捷方式图标”引起的?为什么?
- docker - 部署和保护 Docker 容器和服务器操作系统
- c - 置换基本 BNF 样式字符串
- php - htmlspecialchars() 期望参数 1 在 Laravel 5.8 中是字符串