如果 Angular 中未定义服务器响应,则将变量设置为某个值 2

Setting variable to some value if server response is undefiend in Angular 2

我正在将 Angular 2 与 Redux(ngrx:reducers and effects)结合使用,我完全是这两者的初学者,但我必须使用它们。我向服务器发出请求,如果没有值,我需要将它们设置为某个默认值。我有 activity 和图像。 Activity 是最后一个动作 and/or 消息发生的时间,图像是图像的链接。

这是来自效果的代码:

    @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()
     }

这就是服务器 returns 如果有数据:

    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,这是我想要数据的日期。如果没有数据服务器 returns undefined ,我无法读取它并且应用程序崩溃。所以在那种情况下,我需要设置一些默认值。

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

     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
       }
     }