Angular NGRX @Effect 捕捉所有动作
Angular NGRX @Effect to catch all actions
我有一个 angular 应用程序,我想要一个副作用来调用第三方分析平台的服务。我的想法是做
Any action fires -> Side effect catches everything -> Service to call analytics
话虽如此,我显然不想在每个效果中都添加该流程。我只想在树的顶部有一个 "catch-all" 副作用来捕获所有 Ngrx 操作,而不是分派操作,而是简单地调用服务。我的语法有问题...
@Injectable()
export class AmplitudeEffects {
constructor(private actions$: Actions) {}
@Effect()
private *any action here* = this.actions$.pipe( <--what to put here
ofType(), <-- leave empty to catch everything?
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
// catchError(error => of(new AmplitudeFailure(error)))
)
)
);
}
这是 Effect 的一个很好的用例,我也在 Start using ngrx/effects for this 中给出了这个例子。
要回答您的问题,您可以将 ofType
去掉:
@Effect()
log = this.actions$.pipe(
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
// catchError(error => of(new AmplitudeFailure(error)))
)
)
);
我不确定你是否真的想捕获错误,因为这只是为了记录目的,所以你可以这样做:
@Effect({ dispatch: false })
log = this.actions$.pipe(
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4)
)
);
只要删除 ofType,您的错误处理就会终止 observable,这样 ngrx 就会停止工作,所以我添加了正确的方法来处理 catchError。我应该看起来像那样,但因为我不知道 sendValues 是做什么的,所以我认为它会 return 一个可观察的。
@Effect()
name = this.actions$.pipe(
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
map((x: any)=> x),
catchError((error: any, effect: Observable<Action>) => {
return effect.pipe(startWith(new new AmplitudeFailure(error)));
}
)
)
);
我有一个 angular 应用程序,我想要一个副作用来调用第三方分析平台的服务。我的想法是做
Any action fires -> Side effect catches everything -> Service to call analytics
话虽如此,我显然不想在每个效果中都添加该流程。我只想在树的顶部有一个 "catch-all" 副作用来捕获所有 Ngrx 操作,而不是分派操作,而是简单地调用服务。我的语法有问题...
@Injectable()
export class AmplitudeEffects {
constructor(private actions$: Actions) {}
@Effect()
private *any action here* = this.actions$.pipe( <--what to put here
ofType(), <-- leave empty to catch everything?
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
// catchError(error => of(new AmplitudeFailure(error)))
)
)
);
}
这是 Effect 的一个很好的用例,我也在 Start using ngrx/effects for this 中给出了这个例子。
要回答您的问题,您可以将 ofType
去掉:
@Effect()
log = this.actions$.pipe(
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
// catchError(error => of(new AmplitudeFailure(error)))
)
)
);
我不确定你是否真的想捕获错误,因为这只是为了记录目的,所以你可以这样做:
@Effect({ dispatch: false })
log = this.actions$.pipe(
mergeMap(() =>
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4)
)
);
只要删除 ofType,您的错误处理就会终止 observable,这样 ngrx 就会停止工作,所以我添加了正确的方法来处理 catchError。我应该看起来像那样,但因为我不知道 sendValues 是做什么的,所以我认为它会 return 一个可观察的。
@Effect()
name = this.actions$.pipe(
this.amplitudeService.sendValues(arg1, arg2, arg3, arg4).pipe(
map((x: any)=> x),
catchError((error: any, effect: Observable<Action>) => {
return effect.pipe(startWith(new new AmplitudeFailure(error)));
}
)
)
);