使用 ngrx-effect 在动作发生时调用服务
Use ngrx-effect to call a service when an action occurs
我正在了解效果并尝试在搜索失败时发出警告通知。
我的搜索操作是这样定义的
export enum SearchActionTypes {
SearchActionSearch = '[Search] Action search',
SearchActionFulfilled = '[Search] Action search fulfilled',
SearchActionFailed = '[Search] Action search failed',
}
我的应用程序中有一项可以显示通知的服务,我正尝试在调度 SearchActionFailed 操作时调用此服务。但是,我不知道如何为此建立效果。目前我在这里:
@Injectable()
export class NotificationEffects {
@Effect()
// show error notification when an illegal value is entered into search
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
);
constructor(private actions$: Actions,
private notificationService: NotificationService) {}
}
我想在效果捕捉到动作时调用通知服务 API,调用结构如下:
this.notificationService.createNotification('type', 'message'))
我不需要操作有效负载中的任何内容,只需在分派失败操作时调用此服务即可。但是,我不知道如何构建这种效果。我的主要问题是一个效果必须 return 一个可观察的但我不需要任何我只需要知道什么时候搜索操作失败所以我可以调用服务显示通知警告用户他们的输入是错误的
如果您想收听 createNotification
的发射,只需将 switchMap
传递到您的管道即可:
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
switchMap(() => this.notificationService.createNotification('type', 'message')))
.subscribe(x=>console.log(x)); //gives you emission from this.notificationService
如果您只是想做某事而不关心结果 "side effect",您可以使用 .tap()
:
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
tap(() => this.notificationService.createNotification('type', 'message')))
.subscribe(x=>console.log(x)); //gives you ofType's emission
我正在了解效果并尝试在搜索失败时发出警告通知。 我的搜索操作是这样定义的
export enum SearchActionTypes {
SearchActionSearch = '[Search] Action search',
SearchActionFulfilled = '[Search] Action search fulfilled',
SearchActionFailed = '[Search] Action search failed',
}
我的应用程序中有一项可以显示通知的服务,我正尝试在调度 SearchActionFailed 操作时调用此服务。但是,我不知道如何为此建立效果。目前我在这里:
@Injectable()
export class NotificationEffects {
@Effect()
// show error notification when an illegal value is entered into search
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
);
constructor(private actions$: Actions,
private notificationService: NotificationService) {}
}
我想在效果捕捉到动作时调用通知服务 API,调用结构如下:
this.notificationService.createNotification('type', 'message'))
我不需要操作有效负载中的任何内容,只需在分派失败操作时调用此服务即可。但是,我不知道如何构建这种效果。我的主要问题是一个效果必须 return 一个可观察的但我不需要任何我只需要知道什么时候搜索操作失败所以我可以调用服务显示通知警告用户他们的输入是错误的
如果您想收听 createNotification
的发射,只需将 switchMap
传递到您的管道即可:
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
switchMap(() => this.notificationService.createNotification('type', 'message')))
.subscribe(x=>console.log(x)); //gives you emission from this.notificationService
如果您只是想做某事而不关心结果 "side effect",您可以使用 .tap()
:
searchFailEffect = this.actions$.pipe(
ofType(Search.SearchActionTypes.SearchActionFailed),
tap(() => this.notificationService.createNotification('type', 'message')))
.subscribe(x=>console.log(x)); //gives you ofType's emission