angular - 如何使用 RxJS 跳过可观察值的第一个值?

标签 angular rxjs

在我的 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/

相关文章:

angular - 似乎无法在 Observable 上使用 'first()'(Angular 中的 rxjs)

angular - 如何在 Angular 中顺序发送多个 Http 请求

Angular 2 - 单例服务?

javascript - 如何在 Angular 8 应用程序中添加移动访问 token ?

angular - 使用 *ngFor 和 ngModel 填充对象数组

java - 如何将异步 promise 代码转换为 rxjava

Angular 4 服务方法总是返回未定义而不是 Observable

angular - Angular 2+ 应用程序中的 PEG.js

Angular Material .mat-icon-button 类不存在于 index.html 的样式部分中

Angular等待多个异步post请求然后调用另一个端点