NGRX效果 - 在何处/如何组织效果定义。

时间:2017-03-08 19:42:25

标签: angular ngrx ngrx-effects

我在angular2应用程序中使用@ ngrx / effects,并且在组织不同的效果定义时苦苦挣扎。

我有实体,IdentitySubscription,每个实体都有自己的操作服务IdentityActionsSubscriptionActions,以及它们的效果服务IdentityEffectsSubscriptionEffects

定义了以下行动。

IdentityActions.AuthorizeIdentity()
IdentityActions.OnIdentityAuthorized(identity)
SubscriptionActions.GetSubscriptionList(identity)
SubscriptionACtions.OnSubscriptionsListed(subscriptions)

在授权身份后,我立即想要获得它的订阅列表。 @ngrx/effects如何提倡组织这些效果,以便以后可以追溯/易于查找(例如从现在开始一年)?

在IdentityEffects中:

@Effect()
this._actions.ofType(authActions.AUTHORIZE_IDENTITY))
  .switchMap(() => this.svc.AsyncAuth())
  .switchMap((identity) => authActions.OnIdentityAuthorized(identity))

@Effect()
this._actions.ofType(authActions.ON_IDENTITY_AUTHORIZED)
  .switchMap((identity) => Observable.of(action, subActions.GetSubscriptionList(identty)) 

这在编写时看起来很自然,因为获取订阅列表是获得授权的身份的影响...但我很担心,因为如果开发人员试图追踪订阅列表的获取位置,在IdentityService中挖掘是不直观的。

另一种方法是在不发射的CustomerEffects中注册第二个效果..

@Effect({emit: false})
this._actoions.ofType(authActions.ON_IDENTITY_AUTHORIZED)
  .switchMap((identity) => Observable.of(action, subActions.GetSubscriptionList(identity)) 

从长远来看,这似乎更容易找到...但在编写时感觉不那么自然(我在订阅服务中写了一个身份副作用......)

经过时间考验的方法是什么(如果有足够的时间)?

1 个答案:

答案 0 :(得分:1)

这里没有太多好的反馈,但我想跟进我的方向。

我认为最有意义的是通过受影响的实体对效果进行分组,而不是通过导致效果的原因。

95%的情况下,这会导致效果服务定义仅与一个实体相关......但在某些情况下,可能会有一个或两个效果引用其他内容。

在我的示例中,Identity已经过身份验证,这会导致订阅被加载。

IdentityEffectsService.ts

@Effect()
public AuthorizeIdentity$ = this._actions.ofType(AUTHORIZE_IDENTITY)
  .switchMap(() => this._identitySvc.Authorize())
  .map(identity => this._identityActions.OnIdentityAuthorized(identity))

@Effect()
Public OnIdentityAuthorized$ = this._actions.ofType(ON_IDENTITY_AUTHORIZED)
  .do(identity => console.log(`${identity.name}` logged in!`));

SubscriptionActionsService.ts

@Effect() ListSubscriptions$ = this._actions.ofType(LIST_SUBSCRIPTIONS)
  .map(action => <Identity>action.payload)
  .switchMap(identity=> this._subscriptionSvc.List(identity))
  .map((subs) => this._subscriptionActions.OnSubscriptionsListed(subs))

@Effect() OnSubscriptionsListed$ = this._actions.ofType(ON_SUBSCRIPTIONS_LISTED)
  .do(action => console.log(`${action.payload.length} subscriptions listed.`)

/ * This was the effect in question.
    I've grouped it with the other subscription effects because I believe it
    will be more natural for someone trying to understand how subscriptions
    get filled to find it here in the future. 
*/
@Effect() OnIdentityAuthorized$ = this._actions.ofType(ON_IDENTITY_AUTHORIZED)
  .switchMap(identity => this._subscriptionActions.ListSubscriptions(identity))

显然,仍然希望有一个对中型/大型项目的@Effects模式有更多经验的人。