【问题标题】:Use ngrx-effect to call a service when an action occurs发生动作时使用ngrx-effect调用服务
【发布时间】:2018-04-30 17:29:19
【问题描述】:

我正在了解效果,并尝试在搜索失败时发送警告通知。 我的搜索操作是这样定义的

 export enum SearchActionTypes {
  SearchActionSearch = '[Search] Action search',
  SearchActionFulfilled = '[Search] Action search fulfilled',
  SearchActionFailed = '[Search] Action search failed',
}

我的应用中有一个可以显示通知的服务,我正在尝试在分派 SearchActionFailed Action 时调用此服务。但是,我不知道如何为此构建效果。目前我在这里:

    @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'))

我不需要操作负载中的任何内容,只需在调度失败操作时调用此服务即可。但是,我不知道如何构建这种效果。我的主要问题是效果必须返回一个可观察的,但我不需要任何我只需要知道搜索操作何时失败的东西,因此我可以调用服务来显示通知,警告用户他们的输入是错误的

【问题讨论】:

    标签: angular typescript rxjs ngrx-effects


    【解决方案1】:

    如果您想收听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
    

    如果你只是想做某事而不关心结果,也就是“副作用”,你可以使用.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2019-12-29
      • 2019-02-22
      • 2021-07-21
      • 2018-12-06
      • 2020-11-18
      • 1970-01-01
      相关资源
      最近更新 更多