如何延迟发出错误的Observable

时间:2017-08-01 05:51:44

标签: javascript angular rxjs

假设我有函数进行http调用并返回带有用户详细信息的Observable。

如果用户不存在,则返回发出错误的Observable。

// Get user by id
function getUser(id) {
  return Rx.Observable.create(obs => {
    if (id === 1) {
      obs.next('200 - User found');
      obs.complete();
    } else {
      obs.error('404 - User not found');
    }
  });
}

// This will print "200 - User found" in the console after 2 seconds
getUser(1)
  .delay(2000)
  .subscribe(r => console.log(r));

// !!! Delay will not work here because error emmited
getUser(2)
  .delay(2000)
  .subscribe(null, e => console.log(e));

有没有办法延迟 Observable会发出错误

1 个答案:

答案 0 :(得分:2)

  

我很好奇为什么Observable如果返回错误就不会延迟

以下是delay运算符的源代码:

class DelaySubscriber<T> extends Subscriber<T> {
  ...

  protected _next(value: T) {
    this.scheduleNotification(Notification.createNext(value)); <-------- notification is scheduled
  }

  protected _error(err: any) {
    this.errored = true;
    this.queue = [];
    this.destination.error(err); <-------- error is triggered immediately
  }

  protected _complete() {
    this.scheduleNotification(Notification.createComplete());
  }
}

正如所有其他运算符一样,delay在您的情况下订阅源流 - getUser() - 并通知侦听器。您可以从源代码中看到,当发生错误时它不会安排通知,并立即触发observable上的error方法。

  

我想将每个http请求延迟到API,无论是否成功   不(为了测试应用程序在响应时间过长时的行为方式)

我建议使用Chrome调试工具(网络标签)的throttle功能。