具有Angular4初始状态的Redux / ngRx被错误地修改

时间:2017-10-20 13:11:08

标签: angular redux state ngrx

我目前正在将AngR4状态管理实施到我的Angular4应用程序中,但到目前为止我遇到的问题是,当我在商店中清除某些表单过滤器时,初始状态为'我用来清除值并重置状态似乎在其中设置了属性值。这显然应该保持不变,因为它是用于实例化状态然后不再被触摸的对象。

以下是我的一些代码。请注意,如果/ else语句等稍后要重构,那么目前这是很粗糙的。

控制器:

@Component({
    selector: 'report-exceptions',
    moduleId: module.id,
    templateUrl: '/app/views/reports/report-exceptions.component.html'
})

export class ReportExceptionsComponent {
    @ViewChild('f') form;
    private filtersDropDown: Boolean;
    private formModel: ReportExceptionFilters;
    private formDefaults: Object;
    private viewState = {
        reportExceptionsLoaded: false
    };
    reportExceptions: Array<ReportException> = [];


    constructor(
        private _vehicleService: VehicleService,
        private _accountsService: AccountService,
        private _reportExceptionService: ReportExceptionService,
        private _authenticationService: AuthenticationService,
        private _damageService: DamageService,
        private _boothService: BoothService,
        private _userService: UserService,
        private _store: Store<GlobalState>
    ) {

        this._store.select(store => store.reportExceptionReducer)
            .subscribe((response) => {
                this.formDefaults = response.formDefaults;
                this.formModel = response.formModel;
                this.reportExceptions = response.reportExceptions;
                this.filtersDropDown = response.filtersDropDown;

                if(!this._authenticationService.isSuper()) {
                    this.formModel.accountId = this._authenticationService.accountId;
                }

                if(!this.formDefaults.accounts.length) {
                    this.getAccounts();
                }

                if(this.checkAccountSelected()) {
                    this.getMarques();
                }

                if(this.checkMarqueSelected()) {
                    this.getModels();
                }
            });
    }

    getAccounts() {
        this._accountsService.getAccounts({})return Object.assign({}, state, { formModel: initialState.formModel });
            .subscribe((response) => {
                    this._store.dispatch({ type: 'POPULATE_FORM_DEFAULTS', payload: { ...this.formDefaults, accounts: formHelper.addSelectOption(response.extras.Accounts, 'Name', 'AccountId') }});
                    //this.formDefaults.accounts = formHelper.addSelectOption(response.extras.Accounts, 'Name', 'AccountId');
                },
                (error) => {
                    this._accountsService.processResponseError(error);
                });
    }

    getMarques() {
        this._vehicleService.getMarques({})
        .subscribe((response) => {
                this._store.dispatch({ type: 'POPULATE_FORM_DEFAULTS', payload: {...this.formDefaults, marques: formHelper.addSelectOption(response.extras.Data, 'Name', 'MarqueId') }});
                //this.formDefaults.marques = formHelper.addSelectOption(response.extras.Data, 'Name', 'MarqueId');
            },
            (error) => {
                this._accountsService.processResponseError(error);
            });
    }

    getModels() {
        this._vehicleService.getModels({})
            .subscribe((response) => {
                    this._store.dispatch({ type: 'POPULATE_FORM_DEFAULTS', payload: {...this.formDefaults, models: formHelper.addSelectOption(response.extras.Data, 'Description', 'ModelId') }});
                    //this.formDefaults.models = formHelper.addSelectOption(response.extras.Data, 'Description', 'ModelId');
                },
                (error) => {
                    this._accountsService.processResponseError(error);
                });
    }

    runReports() {
        this.viewState.reportExceptionsLoaded = false;
        const FromDate = this.formModel.dateFrom !== null && this.formModel.timeFrom !== null ? timeHelper.convertToDateTime(this.formModel.dateFrom , this.formModel.timeFrom) : null;
        const ToDate = this.formModel.dateTo !== null && this.formModel.timeTo !== null ? timeHelper.convertToDateTime(this.formModel.dateTo , this.formModel.timeTo) : null;

        this._reportExceptionService.getReportExceptions({
            ReportExceptions: [],
            Criteria: {
                AccountId: this.formModel.accountId,
                VehicleId: this.formModel.vehicleId,
                MakeId: this.formModel.makeId,
                ModelId: this.formModel.modelId,
                //Limit: 5,
                SortBy: 'DESC',
                FromDate,
                ToDate,
                DamageCode: this.formModel.damageCode,
                DamageLocation: this.formModel.damageLocation,
                DamageSeverity: this.formModel.damageSeverities
            }
        })
        .subscribe((response) => {
            this.viewState.reportExceptionsLoaded = true;
            this._store.dispatch({ type: 'POPULATE_REPORT_EXCEPTIONS', payload: { reportExceptions: response.extras.ReportExceptions }});
            this._store.dispatch({ type: 'POPULATE_FILTERS', payload: { formModel: this.formModel }});

            this.viewState.reportExceptionsLoading = true;
        },
        (error) => {
            this._accountsService.processResponseError(error);
        });
    }

    private clearForm() {
        this._store.dispatch({ type: 'RESET_REPORT_EXCEPTIONS' });
        this._store.dispatch({ type: 'CLEAR_FILTERS' });
        this._store.dispatch({ type: 'CLEAR_FORM_DEFAULTS' });
        if(!this._authenticationService.isSuper()) {
            this.formModel.accountId = this._authenticationService.accountId;
        }
        this.form.form.markAsPristine();
        this.form.form.markAsUntouched();
        this.form.form.updateValueAndValidity();

    }

    private toggleFiltersDropdown() {
        this._store.dispatch({ type: 'TOGGLE_FILTER_DROPDOWN', payload: { filtersDropDown: this.filtersDropDown }})
    }

    private checkAccountSelected(): boolean {
        // Check accountId is selected and there are accounts in the form defaults
        if((this.formModel.accountId) && ((undefined !== typeof this.formDefaults.accounts) && (this.formDefaults.accounts.length))) {
            // Check that no marque is currently set and that marques form defaults aren't set
            if((!this.formModel.marqueId) && ((undefined !== this.formDefaults.marques) && (this.formDefaults.marques.length == 0))) {
                return true
            }
        }
    }

    private checkMarqueSelected(): boolean {
        // Check marque is selected and there are marques in the form defaults
        if((this.formModel.marqueId) && ((undefined !== typeof this.formDefaults.marques) && (this.formDefaults.marques.length))) {
            // Check that no model is currently set and that models form defaults aren't set
            if((!this.formModel.modelId) && ((undefined !== this.formDefaults.models) && (this.formDefaults.models.length == 0))) {
                return true
            }
        }
    }
}

减速机:

import { Action, ActionReducer } from "@ngrx/store";
import { ReportExceptionState } from "../interfaces/AppState";
import {User} from "../../classes-and-types/users/User.type";

const initialState: ReportExceptionState = {
    reportExceptions: [],
    selectedReportException: null,
    formModel: {
        vehicleId: null,
        marqueId: null,
        model: null,
        location: null,
        damageCode: null,
        damageLocation: null,
        damageSeverity: null,
        accountId: null,
        user: null,
        dateFrom: null,
        dateTo: null,
        timeFrom: null,
        timeTo: null
    },
    formDefaults: {
        vehicleId: null as string,
        marques: [] as Array<any>,
        models: [] as Array<any>,
        locations:[] as Array<any>,
        damageCodes: [] as Array<any>,
        damageLocations:[] as Array<any>,
        damageSeverities:[] as Array<any>,
        accounts: [] as Array<any>,
        users: [] as Array<User>,
        dateFrom: Date,
        dateTo: Date,
        timeFrom: null as string,
        timeTo: null as string
    },
    filtersDropDown: false
};

export const reportExceptionReducer = (state = initialState, action: Action) => {
    switch(action.type) {
        case 'POPULATE_REPORT_EXCEPTIONS' : {
            return Object.assign({}, state, action.payload);
        }
        case 'RESET_REPORT_EXCEPTIONS' : {
            return Object.assign({}, state, { reportExceptions: initialState.reportExceptions });
        }
        case 'POPULATE_FORM_DEFAULTS' : {
            return Object.assign({}, state, { formDefaults: action.payload });
        }
        case 'CLEAR_FORM_DEFAULTS' : {
            return Object.assign({}, state, { formDefaults: initialState.formDefaults });
        }
        case 'POPULATE_FILTERS' : {
            return Object.assign({}, state, action.payload )
        }
        case 'CLEAR_FILTERS' : {
            return Object.assign({}, state, { formModel: initialState.formModel });
        }
        case 'TOGGLE_FILTER_DROPDOWN' : {
            return Object.assign({}, state, {
                filtersDropDown: !action.payload.filtersDropDown
            });
        }
        default: {
            return state;
        }
    }
};

正如您所看到的,在我的&#39; CLEAR_FILTERS&#39;切换选项我使用以下代码将状态formModel重置回初始状态:

return Object.assign({}, state, { formModel: initialState.formModel });

正在重置&#39; formModel&#39;财产回到初始状态。唯一的问题是,当我在这里放置一个断点时,似乎initialState对象已经被修改了?!任何人都可以看到为什么我的initialState对象在它不应该存在时保持值?

由于

0 个答案:

没有答案