Отправить действие с содержимым файла в NgRx / Angular 7 - PullRequest
0 голосов
/ 20 сентября 2019

У меня есть эффект, что действие отправило файл, и мне нужно отправить действие обратно, чтобы я мог обновить состояние с помощью редуктора.

@Effect()
    uploadChange$: Observable<Action> = this.actions$.pipe(
        ofType(OurActionTypes.UploadChange),
        // map(action => action['payload'])
        map(action => {
            // console.log(action['payload']);

            var input = action['payload'];

            const reader = new FileReader();

            reader.onload = e => {
                const raw = (<FileReader>e.target).result as string;
                const res = JSON.parse(raw);
                console.log(res);
                // this.uploadedSpec = res;
                //  return of(new UploadComplete(res));
            }

            reader.readAsText(input);
        }),
        map((res) => new OurActions.UploadComplete(res))
    );

Я не могу понять, как отправитьРезультаты загрузки на акцию OurActions.UploadComplete.Способ выше имеет res как underfined.Нуждаюсь в помощи с этой вещью.

Ответы [ 2 ]

0 голосов
/ 24 сентября 2019

Используйте что-то вроде этого:

return this.searchService.searchByCriteria(search).pipe(
  map(result => //have an flag in the backend code
   !!result.success ? new fromActions.successAction(result) :
    new fromActions.failureAction(result),
  ),
  catchError(error => of(new errorActions.SystemError(error))),
); 
0 голосов
/ 24 сентября 2019

Ваша проблема в том, что FileReader API является асинхронным.Вам нужно заблокировать свой код и подождать, пока чтение файла не будет завершено.

Попробуйте использовать что-то подобное ... см. Ниже.

ПРИМЕЧАНИЕ. Я предполагаю, что остальная часть вашего кода правильная, поэтомутолько что скопировал.

@Effect()
uploadChange$: Observable<Action> = this.actions$.pipe(
    ofType(OurActionTypes.UploadChange),
    // map(action => action['payload'])
    map(action => {
        // console.log(action['payload']);
        var input = action['payload'];
        // this await should wait until the promise completes
        let result = await new Promise((resolve) => {
           // this is your file reader - asynchronous call
           const fileReader = new FileReader();
           fileReader.onload = (e) => {
              const raw = (<FileReader>e.target).result as string;
              const res = JSON.parse(raw);
              console.log(res);
              // this is a call back to the promise
              resolve(res);
           };
           fileReader.readAsText(input);
        });
        // this is the result of the map function
        return result;
    }),
    map((res) => new OurActions.UploadComplete(res))
);
...