加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 取消基于有效负载而非效果的可观察性

发布时间:2020-12-17 07:11:22 所属栏目:安全 来源:网络整理
导读:我有一个服务,向后端发出http请求我无法控制获取营销页面内容.有时,我需要同时加载多个营销内容.我可以创建一个调用服务的效果. @Effect()marketingContent$= this.actions$ .ofType(LOAD_MARKETING_CONTENT) .switchMap(({ payload }) = this.marketingServ
我有一个服务,向后端发出http请求我无法控制获取营销页面内容.有时,我需要同时加载多个营销内容.我可以创建一个调用服务的效果.

@Effect()
marketingContent$= this.actions$
  .ofType(LOAD_MARKETING_CONTENT)
  .switchMap(({ payload }) => this.marketingService.getContent(payload)
    .map(content => Action.LoadMarketingContentComplete(content))
  )

这工作正常,我可以调用store.dispatch(Action.LoadMarketingContent(‘A’)).

问题是,如果我需要一次加载多个营销内容,.switchMap将取消之前的请求.

store.dispatch(Action.LoadMarketingContent('A'));
store.dispatch(Action.LoadMarketingContent('B'));
// Only `'B'` is loaded since 'A' gets canceled before it completes

我可以使用.mergeMap而不是.switchMap,但是重复的请求不会被取消.

我还可以使用单独的操作来加载每个营销内容,但这需要为每个部分创建一个动作和效果.

有没有办法可以使用.switchMap来取消对相同内容的请求(有效负载相同?)或同时在同一流中取消重复请求时同时发出不同请求的方法?

解决方法

如果你引入了一个CANCEL_MARKETING_CONTENT动作,你可以用mergeMap做这样的事情:

@Effect()
marketingContent$= this.actions$
  .ofType(LOAD_MARKETING_CONTENT)
  .mergeMap(({ payload }) => this.marketingService
    .getContent(payload)
    .map(content => Action.LoadMarketingContentComplete(content))
    .takeUntil(this.actions$.ofType(CANCEL_MARKETING_CONTENT))
  );

基本上,这可以让您根据需要加载任意数量的营销内容,但是在您发送LOAD_MARKETING_CONTENT操作之前,您可以通过调度CANCEL_MARKETING_CONTENT操作来取消任何挂起的加载.

例如,要仅加载A部分,您可以这样做:

store.dispatch(Action.CancelMarketingContent());
store.dispatch(Action.LoadMarketingContent('A'));

要加载A和B,你可以这样做:

store.dispatch(Action.CancelMarketingContent());
store.dispatch(Action.LoadMarketingContent('A'));
store.dispatch(Action.LoadMarketingContent('B'));

实际上,有一种类似但更整洁的方式,它不涉及使用其他动作.

您可以使用与取消触发器相同的有效负载调度相同的操作.例如:

@Effect()
marketingContent$= this.actions$
  .ofType(LOAD_MARKETING_CONTENT)
  .mergeMap(({ payload }) => this.marketingService
    .getContent(payload)
    .map(content => Action.LoadMarketingContentComplete(content))
    .takeUntil(this.actions$
      .ofType(LOAD_MARKETING_CONTENT)
      .skip(1)
      .filter(({ payload: next }) => next === payload)
    )
  );

从内存中,需要跳过跳过效果当前处理的操作.答案假设有效载荷是“A”或“B”等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读