首页 > 解决方案 > 如何使用 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 属性时触发。

如何避免在初始化时触发并仅在用户更改值时触发?

标签: angularrxjs

解决方案


我认为跳过方法在这里会有所帮助

例子

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>


推荐阅读