I am creating an app with Angular 9 and NGRX where I have a post class:
class Post {
id: number;
title: string;
category: string;
}
ParentComponent
displays page 1 of posts and its child, ChildComponent
displays Page 1 of posts with category=book
.
At any moment, the page or category might change or a new post might be created ...
The database is large so I cannot load all posts into the Angular app.
I have a PostService
with the method GetByQuery:
class PostService {
GetByQuery(category: string, page: number) : Observable<Post[]> {
// implementation
}
}
How to update the state if the page
or category
changes or if a new post
created?
Unfortunately, provided information isn't enough because it doesn't show which actions and reducers you have.
Usually for such things when we need to do something extra than a reduce an action people use effects
with them you can listen to the changes of page
, category
or new post
and cause another actions, like reload
data for example.
Here you can find all info: https://ngrx.io/guide/effects
An example (it's old one with decorators, currently createEffect function should be used).
@Injectable()
export class ActivationAdminEffects {
/**
* Sending activation by admin request and processing its result.
*/
@Effect()
public readonly activate$: Observable<Action> = this.actions$.pipe(
ofType(ActivationAdminActions.Activate), // <- waiting this action
// doing side things we need
mergeMap((action: ActivationAdminActionsActivate) =>
this.http.post(this.urlActivationAdmin, action.data).pipe(
mergeMap(() => {
// dispatching a new action once we are done.
return of(new ActivationAdminActionsActivateSuccess());
}),
catchError(
(error: HttpErrorResponse): Observable<Action> => {
if (error.status === 404) {
// an expected error and dispatch of related action
return of(new ActivationAdminActionsActivateFailure());
}
return throwError(error);
},
),
),
),
);
protected readonly urlActivationAdmin: string = `${environment.urlApi}user/activation-admin`;
constructor(protected readonly actions$: Actions, protected readonly http: HttpClient) {}
}