【问题标题】:Delay inside/after subscribe in angular在角度订阅内部/之后延迟
【发布时间】:2019-10-03 13:52:20
【问题描述】:

我在订阅中将isUpdate 标志设置为 true,我必须在延迟一段时间后将其设置回 false,以便显示快速弹出窗口

我尝试过使用.pipe(delay(2000)).subscribe 但是整个回调被延迟了

this.sp.myservice(data).subscribe(
data => {
this.isUpdate = true;
//something like this but not setTimeout
setTimeout(() => 
{
this.isUpdate = false
}, 2000) 
}
);

预期结果:isUpdated 在一段时间内应该为假

【问题讨论】:

  • 为什么不 setTimeout()?

标签: javascript angular rxjs rxjs-observables


【解决方案1】:

有更好的方法来显示弹出窗口。

但要回答你,一个干净的方法可能是:

this.sp.myservice(data).pipe(
  tap(() => this.isUpdate = true),
  delay(5000),
).subscribe(() => this.isUpdate = false);

直播模式:

rxjs.of('some mock value').pipe(
  rxjs.operators.tap(() => console.log('Wait 5 seconds')),
  rxjs.operators.delay(5000),
).subscribe(() => console.log('See ? I am delayed.'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>

编辑

根据您的要求:

this.sp.myservice(data).pipe(
  tap(data => this.isUpdate = this.data && this.data.status && this.data.status.code === 0),
  delay(5000),
  catchError(err => throwError(err))
).subscribe(
  () => this.isUpdate = false,
  err => console.log('an error occured')
);

直播模式:

rxjs.throwError('some error mock value').pipe(
  rxjs.operators.tap(() => console.log('Wait 5 seconds')),
  rxjs.operators.delay(5000),
  rxjs.operators.catchError(err => rxjs.throwError(err))
).subscribe(
  () => console.log('See ? I am delayed.'),
  err => console.log('an error occured')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>

【讨论】:

  • 感谢您的回复,但是我只想在调用成功并且数据具有我需要的属性时显示弹出窗口 - if (data && data.status && data.status. code == 0) { this.isUpdate = true} 是来自 Tap(data=>{}) 中可用服务的数据吗?
  • 点击后订阅没有被调用:(
  • @AjayChandan 嗯,是的,你可以在示例中看到它...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2016-02-07
  • 1970-01-01
  • 2018-09-03
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多