1

I need to upload a file using Ngrx. I don't have to save the file in the Store but I need to pass it between actions, effects and finally services to manage some datas the APIs send me back.

When I choose the file and then click on the upload button I receive the Error: Detected unserializable action on the file parameter.

I tried many solutions like parse and stringify, spreading the object and so on but no one worked. The only solution for now is to set strictActionSerializability on false, but it's not a solution.

I reproduced the situation on this stackblitz: https://stackblitz.com/edit/angular-it6q41

Does anyone have a suggestion on how to solve this?

nicolapiccoli
  • 115
  • 4
  • 10

1 Answers1

0

I'm not sure that manage File content inside an NgRx store is a good practice, however if you want to go in this way, you can retrieve File content as base64 and then pass it to the action :

onSubmit() {
    const file = this.uploadForm.get('file_store').value;
    const signature = file.type;
    const partner_id = this.partner_id;

    const reader = new FileReader();
    reader.onloadend = (e) => {
      this.store.dispatch(
        LoadActions.uploadFile({ content: reader.result, signature, partner_id })
      );
    }
    reader.readAsDataURL(file);
  }

Note : here I changed a little your uploadFile action signature, with a content property in place of dataForm to be more clear.

Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39
  • Thank you @Thierry. This solution solves the problem of the serializability but, unfortunately, I have to send this file to the Google Storage (sorry, I haven't specified this) which doesn't manage the base64 decode. So I receive a Bad image data response. I need to send it as a raw image. – nicolapiccoli Mar 24 '20 at 10:13
  • You can convert it from `base64` to `ArrayBuffer` when you need to send it to backend. see https://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer/21797381 (link updated) – Thierry Falvo Mar 24 '20 at 10:32
  • Tried everything. Converted into base64 the into ArrayBuffer, then Blob and so on. Most of these solutions works, the file arrive and the size is correct, but Google is not able to render the image. – nicolapiccoli Mar 24 '20 at 13:37
  • I had to surrender to this doing some http calls outside of the ngrx flux and just at the end dispatch the final action. – nicolapiccoli Mar 24 '20 at 14:40