NgRx成功行动未派遣

时间:2018-04-22 18:50:01

标签: angular ngrx ngrx-effects

我开始使用NgRx并试图让一个非常简单的场景启动并运行。

问题:

我有一个非常简单的服务,现在只需返回一个硬编码的字符串值,我想通过调度CREATE操作在UI上显示。成功后,应触发CREATE_SUCCESS操作,但永远不会触发CREATE_SUCCESS操作

我公开了3个动作

export const CREATE =                 '[Profile] Create';
export const CREATE_SUCCESS =         '[Profile] Create Success';
export const CREATE_FAIL =            '[Profile] Create Fail';

export class CreateAction implements Action {
    readonly type = CREATE;

    constructor() { }
}

export class CreateSuccessAction implements Action {
    readonly type = CREATE_SUCCESS;

    constructor(public payload: any) { }
}

export class CreateFailAction implements Action {
    readonly type = CREATE_FAIL;

    constructor(public payload: any) { }
}

在减速机中我有以下

export interface State {
    loading: boolean;
    result: Observable<string>;
}

export const initialState: State = {
    loading: false,
    result: Observable.of('Default')
};

export function reducer(state = initialState, action: profile.Actions):State{
    switch (action.type) {
        case profile.CREATE: {
            return {
                ...state,
                loading: true
            };
        }

        case profile.CREATE_SUCCESS: {
            return {
                ...state,
                result: action.payload,
                loading: false
            };
        }

        case profile.CREATE_FAIL: {
            return {
                ...state,
                loading: false,
            };
        }

        default: {
            return state;
        }
    }
}

在效果中我有以下

请注意:我将catch子句移动到switchMap方法中,如许多其他线程所示

@Injectable()
export class ProfileEffects {
    @Effect() create$ = this._actions$
   .ofType(profile.CREATE)
   .switchMap(payload => this._profileService.create$()
       .map(res => ({ type: profile.CREATE_SUCCESS, payload: res }))
       .catch(e => Observable.of({ type: profile.CREATE_FAIL, payload: e })));

  constructor(
      private _profileService: ProfileService,
      private _actions$: Actions
  ) { }
}

在我的组件中,我发送了CreateAction

created$: Observable<string>;

 constructor
 (
     private _store: Store<any>,
     public navCtrl: NavController
 ) {
      this.created$ = this._store.select(s => s.profile.result.value);
 }

create_profile(){
    this._store.dispatch(new CreateAction());
}

在UI上我有

<div>{{ created$ | async }}</div>

在开发工具中很明显,在调度CREATE操作时,但没有CREATE_SUCCESS操作

enter image description here

控制台中没有显示错误消息。

1 个答案:

答案 0 :(得分:0)

尝试进行以下更改:

.switchMap(payload => this._profileService.create$())
.map(res => ({ type: profile.CREATE_SUCCESS, payload: res })

通过移动parantheses,它会在map本身上调用action,而不是create$的结果。这会将CREATE映射到CREATE_SUCCESS