【问题标题】:Issue with Observable/Subject delay/throttle (ngIf & async)Observable/Subject 延迟/节流问题(ngIf 和异步)
【发布时间】:2016-02-15 15:42:13
【问题描述】:

我正在使用@ngrx/store,当请求开始或返回错误时显示通知,如果请求成功则隐藏它。它按预期工作,我想延迟初始通知,因此如果请求很快结束,它不会显示。我尝试了几个与时间相关的 Observable/Subject 运算符:

  • 使用delaybufferTime 消息null,这会导致<notification> 出现错误
  • 使用debounceTime 不显示初始消息,但响应缓慢和错误消息 仍然是null
  • throttleTime 仅显示初始通知并以缓慢的响应隐藏它

如果没有这些*ngIf="(notification |async)" 中的任何一个,它就可以工作,并且仅当通知不是null 时才设置消息

我想我可以用 CSS 转换延迟隐藏 <notification>,但我想知道是否有人知道其他方法来解决这个问题...

@Component({
  template: `<notification [message]="notification |async" *ngIf="(notification |async)"></notification>`
})
export class RootRoute {
  constructor(...) {
    this.notification = this.store.select('notification')
      // None of these solve my issue:
      // .delay(250)
      // .throttleTime(250)
      // .debounceTime(250)
      // .bufferTime(250)
  }
}

export class Service {

  private request(method: any, values: any, endpointsUrl: string, actionType: string, storeSelector?) {
    this.store.dispatch({ type: "SHOW_NOTIFICATION", payload: {code: 200, message: "Getting data from server..."} });

    this._http.request(BASE_URL + endpointsUrl, { body: JSON.stringify(values), method: method })
      .map(response => response.json())
      .map(payload => ({ type: actionType, payload }))
      .subscribe({
        next: action => this.store.dispatch(action),
        error: payload => this.store.dispatch({ type: 'API_ERROR', payload }),
        complete: () => this.store.dispatch({ type: "HIDE_NOTIFICATION" })
      });

    if (storeSelector)
      return this.store.select(storeSelector);
  }

}

【问题讨论】:

  • 你试过timeInterval()吗?
  • @Langley 不确定在这种情况下我将如何使用它。此外,它似乎不是Subject 的有效运算符...
  • 您提到了Observable 而不是SubjectSubject 包装了一个可观察对象,所以它可能也有它或类似的东西。它有助于指定 observable 调用其订阅者的时间,我认为这就是您所说的“我想延迟初始通知,因此如果请求快速结束则不会显示”
  • @ngrx/store.select() 返回主题,我会更新问题...

标签: angular rxjs5 ngrx


【解决方案1】:

我最终得到:

this.store.select('notification')
  .debounceTime(250)
  .subscribe((message: INotification) => this.notification = message);

并为此组件恢复为ChangeDetectionStrategy.Default。我想这是async pipe 的问题之一......

【讨论】:

    【解决方案2】:

    你的问题让我想到另一个问题:

    我没有测试,但是混合 flatMap、delay 和 takeUntil 运算符可以满足您的需求。

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多