Angular2 Ngrx效果服务加载并命中两次我的服务

时间:2017-06-19 06:54:59

标签: angular ngrx-effects ngrx-store

我尝试使用Ngrx特效服务,但似乎它的命令是我的两次

我的发送

this.store.dispatch(new workspacesActions.LoadWorkspaceDetailsActions(this.id));

效果服务:

export class loadDetailsWorkspaceEffectSservice {
    constructor(private actions$: Actions, private WkService: WorkspacesService) {

    }

    @Effect() detailsWorkspace$: Observable<Action> = this.actions$
        .ofType(ActionTypes.LOADWOKSPACESINFOS)
        .switchMap(arg =>

            this.WkService.getDetails(arg.payload))
        .map((workspace) => new workspacesActions.FetchWorkspaceDetailsActions(workspace) );
}

我的服务

 @Injectable()
export class WorkspacesService {  
public _getDetails;

        public getDetails(id: number) { 
        this.spinner.show()
        this._getDetails = this.http.get(config.apiWorkspacesDetailsURL + id, this.jwt())
            .share()
            .map((response: Response) => response.json())
            .catch(this.handleError)
            .finally(() =>  this.spinner.hide());

        return this._getDetails;
    }
}

我的行动

export class LoadWorkspaceDetailsActions implements Action {
  type = ActionTypes.LOADWOKSPACESINFOS;
    constructor(public payload?: any) { }
}

export class FetchWorkspaceDetailsActions implements Action {
  type = ActionTypes.FETCHWOKSPACESINFOS;

   constructor(public payload?: any) { }


}

我的减速机

...
//////////////////
    case WorkspacesActions.ActionTypes.LOADWOKSPACESINFOS:
      return state;

    //////////////////
    case WorkspacesActions.ActionTypes.FETCHWOKSPACESINFOS:
      const resultWS = action.payload;

      return Object.assign(state, {
          workspaceDetails: resultWS.workspace
        });
...

我最终得到两个http请求和2个响应!

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以尝试使用ExhaustMap而不是SwitchMap:

@Effect() 
detailsWorkspace$ = this.actions$.pipe(
    ofType(ActionTypes.LOADWOKSPACESINFOS),
    exhaustMap(arg => this.WkService.getDetails(arg.payload)),
    map(workspace => new workspacesActions.FetchWorkspaceDetailsActions(workspace))
)

或采用新语法(ngrx 8)

detailsWorkspace$ = createEffect(() => 
  this.actions$.pipe(
    ofType(ActionTypes.LOADWOKSPACESINFOS),
    exhaustMap(arg => this.WkService.getDetails(arg.payload)),
    map(workspace => new workspacesActions.FetchWorkspaceDetailsActions(workspace))
);

exhaustMap阻止发送新请求,直到之前完成 https://www.learnrxjs.io/operators/transformation/exhaustmap.html