【问题标题】:Why my effect is running serveral times after action is called?为什么调用 action 后我的效果会运行多次?
【发布时间】:2018-08-30 23:16:20
【问题描述】:

我有这样的效果,即请求多个值以从服务中检索产品。在调度 REQUEST_PRODUCTS 按预期调用一次之后,但是当我尝试转到路由中的其他位置时, this.apiMarketServices 被调用了几次,这会触发路由器导航,这将重定向到上一页。操作 REQUEST_PRODUCTS 被调度一次。为什么这种效应被称为数次?

我是否需要在效果中添加某种停止以避免在返回 GetSuccess 和 GetFailed 之后被调用?

@Effect()
   requestProductsFromMarket = this.actions$
   .ofType(REQUEST_PRODUCTS)
   .withLatestFrom(this.store)
   .switchMap(([action, store]) => {
     const id = store.product.id;
     return this.savedProducts.getProduct(id, 'store');
   })
   .switchMap(_ => this.stateService.getMarketId())
   .switchMap(({ marketId }) =>
     this.apiMarketServices.get(MARKETS_PROFILES + marketId)
   )
   .withLatestFrom(this.store)
   .map(([r, store]) => {
     const ser = r.data.map(s => s.legId);
     const storSer =
       store.product.serIds;
     if (storSer.every(s =>ser.includes(s))) {
        this.router.navigate([
          `/products/edit/${store.products.id}`
        ]);
        return GetSuccess;
    } else {
       return GetFailed;
    }
  })
  .catch(() => of(GetQueryFailed));

【问题讨论】:

  • 我可以处理在最后一个 switchMap 之后添加的 first() 运算符,Promise 称为 servaral 时间,但只能工作一次。使用调度再次调用后,效果不起作用。

标签: javascript angular ngrx ngrx-effects


【解决方案1】:

缺陷的解决方案与 Observable 有关。在调试中“this.apiMarketServices.get(MARKETS_PROFILES + marketId)”被调用了几次,我认为这个服务是缺陷的原因:

.switchMap(({ marketId }) =>
    this.apiMarketServices.get(MARKETS_PROFILES + marketId)
 )

但真正的原因是 stateSevice,这个行为主题在应用的其他部分被 next 更新了。

.switchMap(_ => this.stateService.getMarketId())

为了避免这些调用,我创建了一个函数来从 BehaviorSubject 中检索当前值。

getCurrentMarketId(): ClientData {
   return this.currentMarket.value; // BehaviorSubject
 }

我将此函数添加到每个调度效果调用一次的效果中。

 ...
 .switchMap(([action, store]) => {
    const id = store.product.id;
    return this.savedProducts.getProduct(id, 'store');
 })
 .map(_ => this.stateService.getCurrentMarketId())
 .switchMap(({ marketId }) =>
    this.apiMarketServices.get(MARKETS_PROFILES + marketId)
 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2012-08-01
    • 2015-11-10
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多