Saturday 7 September 2019

Getting JSON data from a file in NGRX / Angular 7 app

I am working off of an existing NgRx/Redux app and new to it (1st app). I have used a previous answer on SO and having trouble adding it to NgRx effects.

I have the following HTML/Angular in my component:

<div class="block">
  <label id="lbl">File </label>
  <input #fileInput type='file' (change)="_onChange($event)"/>
  <button class="btn btn-sm"  (click)="_uploadFile()">Upload The JSON File</button>
</div>

The TS file for the component has:

@Output() uploadFile = new EventEmitter();
    _uploadFile() {
    this.uploadFile.emit();
}

The module TS file:

    uploadFile() {
        this.store.dispatch(new PageActions.UploadFile());
    }

The action file:

export class UploadFile implements Action {
    readonly type = PageActionTypes.UploadFile;
    constructor(public payload: File) { }
}

The effects file:

@Effect()
uploadFile$: Observable<Action> = this.actions$.pipe(
    ofType(PACtions.PageActionTypes.UploadFile),
    map( action => action.payload ),
    // ...
);

From a previous SO answer I see this:

export class AppComponent  {
  uploadedData: any;

  onChange(event) {
    const reader = new FileReader();
    reader.onload = e => {
      const raw = (<FileReader>e.target).result as string;
      const res = JSON.parse(raw);
      this.uploadedData = res;
    }
    reader.readAsText(event.target.files[0]);
  }

  uploadFile() {
    console.log(this.uploadedData);
    // this.store.dispatch(new PageActions.UploadFile(this.uploadedData));
  }

}

How do I get the onChange($event) and uploadedData to fit into my components, effects, and actions files? My component only has @Output ... stuff and the work happens in the effects file.



from Getting JSON data from a file in NGRX / Angular 7 app

No comments:

Post a Comment