如何使用@ngrx / store有效地重置状态?

时间:2017-02-22 19:36:45

标签: javascript angularjs angular ngrx

在过去的几天里,我似乎已经陷入了这个问题。

我们正在开发Angular 2应用程序,我需要为用户创建一个向导来填写表单。

我已成功设法让数据流过向导的每一步,并保存它以便自由来回移动。但是,一旦表单提交,我似乎无法重置它。

我应该补充一点,每个组件都在墙后面。也许更好的解决方案是直接在AppModule注入的单件服务。但我似乎无法使其发挥作用。

到目前为止,这是我的代码:

第1步

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { EventOption } from '../../../events/shared/event-option.model';
import { Store } from '@ngrx/store';
import { NewEventService } from '../shared/new-event.service';
import { Event } from '../../../events/shared/event.model';
import { FriendService } from '../../../friends/shared/friend.service';

@Component({
  selector: 'app-upload-images',
  templateUrl: './upload-images.component.html',
  styleUrls: ['../../../events/new-event/new-event.component.css']
})
export class UploadImagesComponent implements OnInit {
  form: FormGroup;
  private event;
  private images = [];

  constructor(
    private _store: Store<any>,
    private formBuilder: FormBuilder,
    private router: Router,
    private newEventService: NewEventService,
    private friendService: FriendService
  ) {
    _store.select('newEvent').subscribe(newEvent => {
      this.event = newEvent;
    })
  }

  ngOnInit() {
    this.initForm(this.event);
    if (this.event.counter === 0) {
      let friends = this.friendService.getFriends('58aaf6304fabf427e0acc08d');
      for (let friend in friends) {
        this.event.userIds.push(friends[friend]['id']);
      }
    }
  }

  initForm(event: Event) {
    this.images.push({ imageUrl: 'test0', voteCount: 0 });
    this.images.push({ imageUrl: 'test1', voteCount: 0 });
    this.images.push({ imageUrl: 'test2', voteCount: 0 });
    this.images.push({ imageUrl: 'test3', voteCount: 0 });
    this.form = this.formBuilder.group({
      firstImage: [this.event.length > 0 ? this.event.eventOption[0].imageUrl : null],
      secondImage: [this.event.length > 0 ? this.event.eventOption[1].imageUrl : null],
      thirdImage: [this.event.length > 0 ? this.event.eventOption[2].imageUrl : null],
      fourthImage: [this.event.length > 0 ? this.event.eventOption[3].imageUrl : null],
    })
  }

  next() {
    this.event.eventOptions = this.images;
    this.newEventService.updateEvent(this.event);
    this.router.navigate(['events/new-event/choose-friends']);
  }

}

第2步

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { EventOption } from '../../../events/shared/event-option.model';
import { Store } from '@ngrx/store';
import { Event } from '../../shared/event.model';
import { NewEventService } from '../shared/new-event.service';
import { FriendService } from '../../../friends/shared/friend.service';
import { SearchPipe } from '../../../core/search.pipe';

@Component({
  selector: 'app-choose-friends',
  templateUrl: './choose-friends.component.html',
  styleUrls: ['../../../events/new-event/new-event.component.css', './choose-friends.component.css']
})
export class ChooseFriendsComponent implements OnInit {

  private searchTerm = '';
  private event;
  private friends = [];
  private friendsError = false;

  constructor(
    private _store: Store<any>,
    private formBuilder: FormBuilder,
    private router: Router,
    private newEventService: NewEventService,
    private friendService: FriendService
  ) {
    _store.select('newEvent').subscribe(newEvent => {
      this.event = newEvent;
    })
  }

  ngOnInit() {
    this.friends = this.friendService.getFriends('58aaf6304fabf427e0acc08d');
  }

  selectedFriend(friendId: string) {
    return this.friendService.selectedFriend(friendId, this.event.userIds);
  }

  toggleFriend(friendId: string) {
    return this.friendService.toggleFriend(friendId, this.event.userIds);
  }

  toggleAllFriends() {
    return this.friendService.toggleAllFriends(this.friends, this.event.userIds);
  }

  submit() {
    if (this.event.userIds.length > 0) {
      this.newEventService.resetEvent();
      this.router.navigate(['events/vote-events']);
    } else {
      this.friendsError = true;
    }
  }

  back() {
    this.newEventService.updateEvent(this.event);
    this.router.navigate(['events/new-event/upload-images']);
  }

}

活动服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Store, Action } from '@ngrx/store';
import { Event } from '../../../events/shared/event.model';
import { EventOption } from '../../../events/shared/event-option.model';
import { newEvent, newEventModel } from './new-event.reducer';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/find';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class NewEventService {
  public newEvent$: Observable<newEventModel>;

  constructor(private store: Store<newEventModel>) {
    this.newEvent$ = this.store.select('newEvent');
  }

  getEvent(event) {
    return this.store.dispatch({
      type: 'GET_EVENT',
      payload: event
    })
  }

  updateEvent(event) {
    return this.store.dispatch({
      type: 'UPDATE_EVENT',
      payload: event
    })
  }

  resetEvent() {
    return this.store.dispatch({
      type: 'RESET_EVENT',
    })
  }

}

事件减速器

import { EventOption } from '../../shared/event-option.model';
import { EventType } from '../../shared/event-type.model';
import { ActionReducer, Action } from '@ngrx/store';
import { Event } from '../../shared/event.model';
import { FriendService } from '../../../friends/shared/friend.service';

export interface newEventModel {
  eventOptions: EventOption[];
  eventTypeId: number,
  duration: number,
  comment: string,
  privacyId: number,
  isGlobal: boolean,
  id: string,
  userIds: string[],
  counter: number
}

let blankState: newEventModel = {
  eventOptions: [],
  eventTypeId: null,
  duration: 1440,
  comment: '',
  privacyId: 0,
  isGlobal: false,
  id: '',
  userIds: [],
  counter: 0
}

let initialState: newEventModel = {
  eventOptions: [],
  eventTypeId: null,
  duration: 1440,
  comment: '',
  privacyId: 0,
  isGlobal: false,
  id: '',
  userIds: [],
  counter: 0
}

export const newEvent: ActionReducer<newEventModel> = (state: newEventModel = initialState, action: Action) => {
  // return new state
  switch (action.type) {
    case 'GET_EVENT':
      return state;
    case 'UPDATE_EVENT':
      action.payload.counter = action.payload.counter + 1;
      return action.payload;
    case 'RESET_EVENT':
      return Object.assign({}, state, {
        eventOptions: [],
        eventTypeId: null,
        duration: 1440,
        comment: '',
        privacyId: 0,
        isGlobal: false,
        id: '',
        userIds: [],
        counter: 0
      });
    default:
      return state;
  }
}

如果需要,我可以提供一个工作的plunkr,但我需要先创建它。

TLDR:如何在@ ngrx / store上重置状态?

感谢您提供的任何帮助!

5 个答案:

答案 0 :(得分:4)

您可以使用initialStateObject.assign的所有属性复制到新对象,从而将缩减器中的状态重置为initialState

export const newEvent: ActionReducer<newEventModel> = (state: newEventModel = initialState, action: Action) => {
  // return new state
  switch (action.type) {
    // ...
    case 'RESET_EVENT':
      return Object.assign({}, initialState);
    // ...
  }
}

关于减速机的说明

reducer应该是pure function,所以不应该修改参数。您的UPDATE_EVENT需要进行一些调整:

case 'UPDATE_EVENT':
  let counter = { counter: action.payload.counter + 1 };
  return Object.assign({}, action.payload, counter);

要遵循的模式是Object.assign({}, source1, source2, ...),其中source1source2等包含要分配的属性。 source1中的属性会被source2等中的重复属性覆盖。

答案 1 :(得分:4)

还有一种更简单的方法,您只需要设置initialState而不是state

  const reducer = createReducer(initialState,
  on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
    ...initialState
  })),

答案 2 :(得分:3)

her answer中,Noy Levi对这个问题有正确的想法,该问题将initialState分配回状态,但是,有一种方法可以自动为每个reducer分配initialState。

要理解的关键概念是,如果传递给化简器的'state'的值是'undefined'(不是'null',则需要是'undefined'),那么化简器会自动将其分配给'state'创建后的initialState提供给化简器。由于这种默认行为,您可以创建一个“ metareducer”来识别一个动作,例如“ logout”,然后将“ undefined”状态传递给所有随后调用的reduce。

this article中关于redux,this article关于NgRx以及this answer关于NgRx对此行为进行了很好的描述。

相关代码如下:

export function logoutClearState(reducer) {
    return function (state, action) {
        if (action.type === ActionTypes.LOGOUT) {
            state = undefined;
        }
        return reducer(state, action);
    };
}

@NgModule({
    imports: [
        StoreModule.forRoot(reducers, { metaReducers: [logoutClearState] }),
    ],
    declarations: [],
    providers: [],
})

答案 3 :(得分:1)

我假设您的RESET_EVENT假设返回一个新对象。虽然您使用state数据和另一个对象填充对象:

case 'RESET_EVENT':
  return Object.assign({}, state, {
    eventOptions: [],
    eventTypeId: null,
    duration: 1440,
    comment: '',
    privacyId: 0,
    isGlobal: false,
    id: '',
    userIds: [],
    counter: 0
  });

Object.assign的语法为Object.assign(target, ...sources),您提供两个项目作为来源:state以及包含eventOptionseventTypeId等的对象

相反,您需要返回Object.assign({}, initialState);

答案 4 :(得分:1)

抱歉,我休了一天假以便参加一些考试。我最后通过执行以下操作“解决”它:

....
case 'RESET_EVENT':
  action.payload.eventOptions = blankState.eventOptions;
  action.payload.eventTypeId = blankState.eventTypeId;
  action.payload.duration = blankState.duration;
  action.payload.comment = blankState.comment;
  action.payload.privacyId = blankState.privacyId;
  ....
  return action.payload;
....

它可能不是最漂亮或最好的解决方案,但至少它可行。感谢@iblamefish和所有人的所有帮助。

相关问题