3

我尝试使用 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 个响应!

感谢您的帮助

4

1 回答 1

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))
);

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

于 2019-11-14T14:34:15.657 回答