尽管更新了ngrx有效负载中的数据,但更新UI时出现问题

时间:2020-03-31 06:57:54

标签: angular state ngrx

最近几天我一直在努力更新UI,但找不到解决方案。

方案::我希望能够从事件编辑组件中编辑事件,然后在完成更新后将其重定向回事件详细信息组件中的同一事件。我可以在后端进行更改,并且ngrx状态向我显示了Redux DevTools中的正确数据。问题是,当我按更新并重定向到事件详细信息时,我会看到事件的旧版本,直到刷新页面为止。为什么只有按f5时一切都应该正常工作?

谢谢..

事件详细信息组件(我应该在其中看到更新的事件)

import { Component, OnInit, ChangeDetectionStrategy, OnDestroy, ViewEncapsulation} from 
'@angular/core';

import { AppState } from 'src/app/core/state';
import { Store, select } from '@ngrx/store';
import * as fromEvents from '../../state/events';
import { Observable, Subscription } from 'rxjs';
import { Event } from 'src/app/shared/models';

import { ActivatedRoute } from '@angular/router';
import { AlertifyService } from 'src/app/core/services/alertify.service';

import * as fromSession from '../../../core/state/session';

@Component({
  selector: 'ex-event-detail',
  templateUrl: './event-detail.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrls: ['./event-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class EventDetailComponent implements OnInit, OnDestroy {
  subscription: Subscription;
  eventId: any;
  ev$: Observable<Event>;
  eventUsers$: any;
  userId: number;

  constructor(
    private store$: Store<AppState>,
    private alertify: AlertifyService,
    private activatedRoute: ActivatedRoute,
  ) {
    this.store$.select(fromSession.selectUser).subscribe(user => (this.userId = user.id));
  }

  ngOnInit() {
    this.subscription = this.activatedRoute.params.subscribe(params => {
      this.eventId = params['id'];
    });
    this.loadEvent();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadEvent() {
    this.store$.dispatch(new fromEvents.LoadEvent(+this.eventId));
    this.ev$ = this.store$.pipe(select(fromEvents.getCurrentEvent));

    this.eventUsers$ = this.store$.pipe(select(fromEvents.getCurrentUsers));
    console.log(this.ev$);
  }
}

事件编辑组件(我在其中编辑事件的地方)

import { Component, OnInit, ChangeDetectionStrategy, OnDestroy, ChangeDetectorRef } from '@angular/core';

import { Store, select } from '@ngrx/store';
import { AppState } from 'src/app/core/state';
import { Observable} from 'rxjs';
import { Event } from 'src/app/shared/models';
import * as fromEvents from '../../state/events';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'ex-event-edit',
  templateUrl: './event-edit.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrls: ['./event-edit.component.scss']
})
export class EventEditComponent implements OnInit, OnDestroy {
  ev$: Observable<Event>;
  eventEditForm: FormGroup;

  constructor(private store$: Store<AppState>, private fb: FormBuilder) {}

  ngOnInit() {
    this.ev$ = this.store$.pipe(select(fromEvents.getCurrentEvent));

    this.createEventEditForm();
  }

  ngOnDestroy() {}

  createEventEditForm() {
    this.ev$.subscribe(ev => {
      this.eventEditForm = this.fb.group({
        id: [ev.id],
        title: [ev.title, Validators.required],
        description: [ev.description, Validators.required],
        image: [ev.image],
        location: [ev.location, Validators.required],
        startdate: [ev.startDate],
        starttime: [ev.startDate],
        enddate: [ev.endDate],
        endtime: [ev.endDate]
      });
    });
  }

  updateEvent() {
    if (this.eventEditForm.valid) {

      const ev = Object.assign({}, this.eventEditForm.value);
      this.store$.dispatch(new fromEvents.UpdateEvent(ev));
    }
  }
}

这是状态代码

/*--------------UpdateEventActions--------------*/ 

export class UpdateEvent implements Action {
  readonly type = ActionTypes.UPDATE_EVENT;

  constructor(public payload: Event) {}
}

export class UpdateEventSuccess implements Action {
  readonly type = ActionTypes.UPDATE_EVENT_SUCCESS;

  constructor(public payload: Update<Event>) {}
}

export class UpdateEventError implements Action {
  readonly type = ActionTypes.UPDATE_EVENT_ERROR;

  constructor(public payload: string) {}
}


/*--------------UpdateEffect--------------*/ 

@Effect()
  updateEvent$: Observable<Action> = this.actions$.pipe(
    ofType<eventsActions.UpdateEvent>(eventsActions.ActionTypes.UPDATE_EVENT),
    map((action: eventsActions.UpdateEvent) => action.payload),
    switchMap((event: Event) =>
      this.eventResource.updateEvent(event).pipe(
        map(
          (updatedEvent: Event) =>
            new eventsActions.UpdateEventSuccess({
              id: updatedEvent.id,
              changes: updatedEvent
            })
        ), 
        tap(() => this.router.navigate(['/event/' + event.id])),
        catchError(err => of(new eventsActions.UpdateEventError(err)))
      )
    )
  );

/*--------------UpdateReducer--------------*/ 
case eventsActions.ActionTypes.UPDATE_EVENT_SUCCESS: {
      return adapter.updateOne(action.payload, state);
    }

    case eventsActions.ActionTypes.UPDATE_EVENT_ERROR: {
      return {
        ...state,
        error: action.payload
      };
    }

/*--------------UpdateSelectors--------------*/ 

import { createSelector } from '@ngrx/store';

import { AppState } from '../../../core/state';
import { adapter } from './events.adapter';

const { selectAll } = adapter.getSelectors();

export const selectState = (state: AppState) => state.event.evs;

export const getEvents = createSelector(selectState, selectAll )

export const getEventsLoading = createSelector(selectState, state => state.loading);

export const getEventsLoaded = createSelector(selectState, state => state.loaded);

export const getError = createSelector(selectState, state => state.error);

export const getCurrentEventId = createSelector(selectState, state => state.selectedEventId);

export const getCurrentEvent = createSelector(selectState, getCurrentEventId, state => state.entities[state.selectedEventId]); //this is the one i use to list the specific event

export const getCurrentUsers = createSelector(selectState, getCurrentEventId, state => state.users);

1 个答案:

答案 0 :(得分:0)

可以在更改Data[grep("^SR_",Data[,"Abbreviation"]),] 的地方提供代码吗? 在上面的代码中,我看到了除字段已更新的地方以外的所有内容,并且我认为这可以解决您的问题。