-1

I have boilerplate from another contractor and am new to NgRx (and Angular in general - it's my first app). I need to get the store in JSON form output via a text file. I am stuck on the @effect:

@Effect({ dispatch: false })
 downloadJSON$ = this.actions$.pipe(
       ofType(WorkActionTypes.DownloadJSON),
       withLatestFrom(this.store.select(fromApp.getWorkState)),
       map(([empty, work]) => {

           //stuck on this part of the code
       })
   );

Can I get some direction/help/code? I am trying to do it without using a library too. Thanks.

cdub
  • 24,555
  • 57
  • 174
  • 303

1 Answers1

0

You can try injecting DOCUMENT object in your effects.

import { DOCUMENT } from '@angular/common';

@Injectable()
export class AppEffects {
  constructor(
    private actions$: Actions,
    @Inject(DOCUMENT) private document: Document) { }

  @Effect({ dispatch: false })
  downloadJSON$ = this.actions$.pipe(
    ofType(WorkActionTypes.DownloadJSON),
    withLatestFrom(this.store.select(fromApp.getWorkState)),
    map(([empty, work]) => {

      const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(work));
      const downloadAnchorNode = this.document.createElement('a');
      downloadAnchorNode.setAttribute("href", dataStr);
      downloadAnchorNode.setAttribute("download", "store.json");
      this.document.body.appendChild(downloadAnchorNode); // required for firefox
      downloadAnchorNode.click();
      downloadAnchorNode.remove();

    })
  );

}

Credits

Pankaj
  • 538
  • 4
  • 13