【问题标题】:Rxjs Wait OperatorRxjs 等待操作符
【发布时间】:2021-12-01 17:18:43
【问题描述】:

我正在与 rxjs 运算符作斗争。其实我有这个例子。

constructor() {}

  ngOnInit(): void {
    //this.demo();
  }

  demo = () => {
    const obs = interval(15000);

    obs.subscribe(this.handleMessage.bind(this));
  };
  handleMessage() {
    alert('Hello');
  }

当用户没有点击 OK 并发出警报时,我想忽略所有 obs 事件。我正在考虑添加一个新的 observable 以忽略 obs 事件,但它不起作用

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, interval, Observable, Subscription } from 'rxjs';
import { filter, first, switchMap, take } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';
  instance = new BehaviorSubject({ status: true });
  instanceObs$ = this.instance.asObservable();
  subscription = new Subscription();
  constructor() {}

  ngOnInit(): void {
    this.demo();
  }

  demo = () => {
    const obs$ = interval(5000);
    this.subscription = obs$
      .pipe(waitFor(this.instanceObs$.pipe(filter((r) => r.status))), take(1))
      .subscribe(this.handleMessage.bind(this));
  };
  handleMessage() {
    this.instance.next({ status: false });
    alert('Hello');
    this.instance.next({ status: true });
  }
}
export function waitFor<T>(signal: Observable<any>) {
  return (source: Observable<T>) =>
    signal.pipe(
      first(),
      switchMap((_) => source)
    );
}

Alert 是一个示例,我在带有异步运算符的实际场景中使用确认 devextrem

async handleUpdateFromAnotherTab(message: IRocketBroadcastMessage) {
    this.instance.next({ status: false });
    let result = await confirm(
      'Data has been updated from another tab. Would you like to reload it?',
      'Warning'
    );
    if (result) {
      window.location.reload();
    }
    this.instance.next({ status: true });
  }
}

StackBlitz

【问题讨论】:

    标签: angular rxjs rxjs6


    【解决方案1】:

    试试这个。

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      name = 'Angular';
      alerted = false;
      subscription = new Subscription();
    
      constructor() {}
    
      ngOnInit(): void {
        this.demo();
      }
    
      demo = () => {
        const obs$ = interval(5000);
        this.subscription = obs$
          .pipe(filter( () => this.alerted === false))
          .subscribe(this.handleMessage());
      };
    
      handleMessage = () => {
        this.alerted = true;
        alert('Hello');
        this.alerted = false;
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2023-04-05
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多