Alexander Kosorukov
Alexander Kosorukov

Reputation: 1

NGRX problem: service that has to fill the state is called after successful action

The state is filled by Http service request to the .NET core API, where the data are loaded from SQL server database. This action is started by button click:

<button (click)="Elements()">getPostElements</button>
@Component({
  selector: 'app-list-state-data',
  templateUrl: './list-state-data.component.html',
  styleUrl: './list-state-data.component.css'
})
export class ListStateDataComponent {
  posts$: Observable<PostInterface[]>;

  constructor(
    private store: Store<AppStateInterface>) {
    this.posts$ = this.store.pipe(select(postsSelector));
  }

  public Elements(): void {
    this.store.dispatch(
      PostsActions.getPosts()
    );
  }
}

Effects.ts:

@Injectable()
export class PostsEffects {

  getPosts$ = createEffect(() =>
    this.actions$.pipe(
      ofType(PostsActions.getPosts),
      mergeMap(() => {
        return this.postsService.getPosts().pipe(
          map((posts) => PostsActions.getPostsSuccess({ posts })),
          catchError((error) =>
            of(PostsActions.getPostsFailure({ error: error.message }))
          )
        );
      })
    )
  );

  createPost$ = createEffect(() =>
    this.actions$.pipe(
      ofType(PostsActions.createPost),
      mergeMap(({ post }) => {
        return this.postsService.createPost(post).pipe(
          map((post) => PostsActions.createPostSuccess({ post })),
          catchError((error) =>
            of(PostsActions.createPostFailure({ error: error.message }))
          )
        );
      })
    )
  );

  constructor(private actions$: Actions, private postsService: PostsService) {
  }
}

The problem is:

Debugger shows that the service request: this.postsService.getPosts() is executed after this line: map((posts) => PostsActions.getPostsSuccess({ posts })), and therefore the variable "posts" is empty.

But when I click the button "getPostElements" second time - it fills correctly the state (posts$). I should not click the button twice, the state should be filled by the first button click. Could you please suggest - what I have to change in the code?

I tried to use .pipe(delay(1000)) after this.postsService.createPost(post) - it did not help.

Upvotes: 0

Views: 23

Answers (0)

Related Questions