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

abu*_*ich 2 javascript angularjs ngrx angular

最近几天,我似乎在这件事上陷入困境。

我们正在开发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']);
  }

}
Run Code Online (Sandbox Code Playgroud)

第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']);
  }

}
Run Code Online (Sandbox Code Playgroud)

活动服务

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',
    })
  }

}
Run Code Online (Sandbox Code Playgroud)

事件减少器

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

感谢您提供的任何帮助!

Joh*_*n Q 10

Noy Levi 在回答这个问题时的想法是正确的,它将初始状态分配回状态,但是,有一种方法可以自动为每个减速器分配初始状态。

要理解的关键概念是,如果传递给reducer的“state”的值是“undefined”(不是“null”,它需要是“undefined”),那么reducer将自动将提供给“state”的initialState分配给“state”创建时的减速器。由于这种默认行为,您可以创建一个“metareducer”来识别操作,例如“注销”,然后将“未定义”状态传递给所有后续调用的减速器。

这种行为在这篇关于 redux 的文章、这篇关于 NgRx 的文章以及这篇关于 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: [],
})
Run Code Online (Sandbox Code Playgroud)

  • 太感谢了!这是一个非常优雅的解决方案,可以免费“扩展”。你的回答应该被接受。 (2认同)

小智 9

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

  const reducer = createReducer(initialState,
  on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
    ...initialState
  })),
Run Code Online (Sandbox Code Playgroud)


ibl*_*ish 5

您可以initialState通过Object.assign将的所有属性复制initialState到新对象中,来将状态重置为reducer中的状态。

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

关于减速器的注意事项

减速器应为纯函数,因此不应修改参数。您UPDATE_EVENT需要进行一些调整:

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

到后续的图案是Object.assign({}, source1, source2, ...)其中source1source2等包含要分配的属性。中的属性source1source2等中的重复属性覆盖。