如果服务器响应在Angular 2

时间:2017-08-21 09:39:26

标签: angular ionic2 redux undefined reducers

我将Angular 2与Redux结合使用(ngrx:减速器和效果),我在这两者中都是初学者,但我必须使用它们。我向服务器请求,如果没有值,我需要将它们设置为某个默认值。我有活动和图像。活动是指最后一次动作和/或消息发生时,图像是指向图像的链接。

以下是效果代码:

    @Effect() getActivity$ = this.actions$
      .ofType(DashboardActions.GET_ACTIVITY)
      .withLatestFrom(this.store, (action, state) => ({
        senior: state.senior.globalSenior.id,
        date: action.payload
      }))
      .switchMap((options) => {
        return this.dashboardService.getActivity({
          id: options.senior,
          date: options.date
        })
        .map((res) => ({ type: DashboardActions.GET_ACTIVITY_SUCCESS, payload: res }))
        .catch(() => Observable.of({ type: DashboardActions.GET_ACTIVITY_ERROR }))
      })

    @Effect() getImages$ = this.actions$
      .ofType(DashboardActions.GET_IMAGES)
      .withLatestFrom(this.store, (action, state) => ({
        senior: state.senior.globalSenior.id,
        date: action.payload
      }))
      .switchMap((options) => {
        return this.dashboardService.getImages({
          id: options.senior,
          date: options.date
        })
          .map((res) => ({ type: DashboardActions.GET_IMAGES_SUCCESS, payload: res }))
          .catch(() => Observable.of({ type: DashboardActions.GET_IMAGES_ERROR }))
      })

以下是reducer的代码:

    export interface State {
      activity: any,
      images: any
    }

    const initialState: State = {
      activity: null,
      images: null
    }

    export function reducer (state = initialState, action: Action): State {
      switch (action.type) {
        case DashboardActions.GET_ACTIVITY_SUCCESS:
          return Object.assign({}, state, {
            activity: action.payload
          })

        case DashboardActions.GET_IMAGES_SUCCESS:
          return Object.assign({}, state, {
            images: action.payload
          })

        default:
          return state
      }
    }

以下是我在html(组件)模板中使用它的地方:

        <ion-grid class="dashboard-table">
            <ion-row>
              <ion-col *ngFor="let message of (activity$ | async)?.data[0]" text-center no-padding>
                <span [ngClass]="{'dot-message dot-message--big':(message === 1)}" *ngIf="message"></span>
                <span [ngClass]="{'dot-message':(message !== 1)}" *ngIf="!message"></span>
              </ion-col>
            </ion-row>
            <ion-row>
              <ion-col *ngFor="let motion of (activity$ | async)?.data[1]" text-center no-padding>
                <span [ngClass]="{'dot-motion dot-motion--big':(motion === 1)}" *ngIf="motion"></span>
                <span [ngClass]="{'dot-motion':(motion !== 1)}" *ngIf="!motion"></span>
              </ion-col>
              <ion-col col-6 *ngFor="let image of (images$ | async)" no-padding class="images__col">
                <img (click)="onLittleImageClick(image.data)" [src]="image?.data" />
                <span class="images__time">{{ (activity$ | async)?.last_motion_time | date:'h:mm:a' }}</span>
              </ion-col>
            </ion-row>
        </ion-grid>

     constructor (
       public navCtrl: NavController,
       public modalCtrl: ModalController,
       private store: Store<fromRoot.AppState>
     ) {
       this.activity$ = this.store.select(s => s.dashboard.activity)
       this.images$ = this.store.select(s => s.dashboard.images)
       this.hideSwipeUpButton()
     }

如果有数据,这就是服务器返回的内容:

    activity {
      "data":[[1,1,0,1,0,1,0,1,0,0,1,0],[0,0,0,1,1,0,1,0,1,1,1,0]],
      "types":["Message","Motion"],
      "graph_start":0,
      "graph_end":1320,
      "graph_step":120,
      "last_message_time":"2017-07-11T20:17:02.118Z",
      "last_motion_time":"2017-07-11T21:24:02.118Z"
    }
    images {
      data: "https://us.123rf.com/450wm/budabar/budabar1511/budabar151100162/48605730-old-man-sitting-on-bed-and-holding-head-with-hands.jpg?ver=6"
      id: "30230de6-471e-4866-aa6d-ff3e6dd1eee0"
    }

所以实际上,我正在进行服务器options.date,这是我想要数据的日期。如果没有数据服务器返回未定义,我无法读取它并且应用程序崩溃。所以在这种情况下,我需要设置一些默认值。

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。首先,我在reducer中定义了默认值,并将我的返回值设置为Object.assign()。所以在我的reducer中,如果从服务器返回一个空数组,reducer将返回默认值。所以最后我的减速机看起来像这样:

     const defaultActivityValues = {
       data:[[0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0]],
       types:["Message","Motion"],
       graph_start:0,
       graph_end:0,
       graph_step:0,
       last_message_time:"2017-01-01T20:17:02.118Z",
       last_motion_time:"2017-01-01T21:24:02.118Z"
     }
     export interface State {
       activity: any,
       images: any
     }

     const initialState: State = {
       activity: null,
       images: null
     }

     export function reducer (state = initialState, action: Action): State {
       switch (action.type) {
         case DashboardActions.GET_ACTIVITY_SUCCESS:
           return Object.assign({}, state, {
             activity: Object.assign({}, defaultActivityValues, action.payload)
         })
         case DashboardActions.GET_IMAGES_SUCCESS:
           return Object.assign({}, state, {
             images: action.payload
         })
         default:
           return state
       }
     }