我正在开发一个使用ngrx存储和效果的角度应用程序。我得到
从我的组件调度操作时出现“ TypeError:无法冻结”
错误。我是为文件上传功能编写的。我认为我正在改变状态,但是无法弄清楚在哪里以及如何解决它。 这是我的详细代码:
Actions:
export enum FileUploadActionTypes {
UploadFile = '[File Upload] Upload File',
UploadFileSuccess = '[File Upload] Upload File Success',
UploadFileFailure = '[File Upload] Upload File Failure'
}
export class UploadFile implements Action {
readonly type = FileUploadActionTypes.UploadFile;
constructor(public payload: any) {}
}
export class UploadFileSuccess implements Action {
readonly type = FileUploadActionTypes.UploadFileSuccess;
constructor(public payload: any) {}
}
export class UploadFileFailure implements Action {
readonly type = FileUploadActionTypes.UploadFileFailure;
constructor(public payload: any) {}
}
export type FileUploadActionsUnion = UploadFile | UploadFileSuccess | UploadFileFailure;
Service:
export class FileUploadService {
constructor(private httpClient: HttpClient) {
}
uploadFile(file: any): Observable<any> {
return this.httpClient.post<any[]>('/api-url/', file);
}
}
Effect:
@Effect()
uploadFile$ = this.actions$.pipe(
ofType<UploadFile>(FileUploadActionTypes.UploadFile),
mergeMap(action => this.fileUploadService.uploadFile(action.payload).pipe(
map(result => new UploadFileSuccess(result)),
catchError(error => of(new UploadFileFailure(error)))
))
)
Reducer:
export interface State {
fileUploadSuccessResponse: any,
fileUploadFailureResponse: any
}
export const initialState = {
fileUploadSuccessResponse: null,
fileUploadFailureResponse: null
}
export const getFileUploadSuccessResponse = state => state.fileUploadSuccessResponse;
export const getFileUploadFailureResponse = state => state.fileUploadFailureResponse;
export function reducer(state: State = initialState, action: FileUploadActionsUnion):State {
switch(action.type) {
case FileUploadActionTypes.UploadFile: {
return {
...state
}
}
case FileUploadActionTypes.UploadFileSuccess: {
return {
...state,
fileUploadSuccessResponse: action.payload
}
}
case FileUploadActionTypes.UploadFileFailure: {
return {
...state,
fileUploadFailureResponse: action.payload
}
}
default: {
return state;
}
}
}
答案 0 :(得分:2)
似乎您正在使用ngrx-store-freeze
npm软件包。该软件包可确保您对商店所做的任何更新都不会直接变异。此过程的一部分是将Object.freeze()
应用于您要分派的操作的payload
对象。即this.store.dispatch(new UploadFiles(file))
。
<input type="file">
控件的默认行为是将其值另存为FileList
对象。由于此对象是原始数据类型,因此Javascript会将其视为只读,从而阻止您写入其属性。这也解释了为什么Object.freeze()
失败的原因,因为它无法将冻结应用于只读数据类型。
最近我使用NGRX和<input type="file">
表单控件遇到了相同的问题。解决方法是将FileList
克隆到一个新对象中,然后再分发到商店。
onChange(control: FormControl) {
const primitiveFileList: FileList = control.value;
const clonedFiles = { ...primitiveFileList };
this.store.dispatch(new UploadFiles(clonedFiles));
}
如果其他人知道此方法有任何潜在的缺点,我将不胜感激。