Angular2 / ngrx和API调用

时间:2016-09-09 16:11:54

标签: angular ngrx

我最近一直在探索ngrx(ngrx / store)。 我在网上研究了一些经典的例子(todo应用程序)。很好的例子。现在我想通过让我的ngrx应用程序进行一些API调用来将它提升到一个新的水平。是否有示例或指南如何设置ngrx(redux)应用程序来调用和处理api调用?

我理解在我的redux应用程序的上下文中的api调用是副作用(函数式编程范例)。 我想知道在redux应用程序中如何/在哪里实现API调用。

2 个答案:

答案 0 :(得分:10)

答案 1 :(得分:0)

为什么会有副作用? 因为ngrx表示您的reducer应该是纯函数,所以您不能在reducer中使用API​​异步调用。 你的减速器做什么? ->它会更新您的状态并返回更新后的状态。 那么如何在reducer中创建API? ->为此,ngrx在@ ngrx / effect中提供效果。

像reducer那样,将大小写切换为已识别的动作,因此效果也将订阅所有动作,并监听所有动作。

效果如何识别行动? ->

就像在减速器中一样-

export function reducer(state = initialState, action: myActions.Actions) {
  switch (action.type) {    
    case myActions.actionType.SEND_CANDIDATE_OTP: {      
      return Object.assign({}, state, {otp:'test'});
    }
}

效果看起来像->

    export class CandidateEffect {
      @Effect()
      sendCandidateOTP$: Observable<Action> = this.action$
        .ofType(myActions.actionType.SEND_CANDIDATE_OTP)
        .pipe(
          switchMap((action: myActions.GetCandidateAction) => {
            const input: myModel.GetCandidateInput = action.payload;
            return this.candidateService.SendCandidateOTP(input).pipe(
              map(resp => {
                return new myActions.SendCandidateOTPSuccessAction(resp);
              }),
              catchError((err, caught) => {
                return of(new myActions.SendCandidateOTPFailAction(err));
              })
            );
          })
        );
}

在上面的代码中,您将使用ngrx中的typeOf关键字标识操作。