首页 > 解决方案 > 当过滤器更改或使用 NGRX 创建新实体时更新 redux 状态

问题描述

我正在使用 Angular 9 和NGRX创建一个应用程序,其中我有一个帖子类:

    class Post { 
      id: number; 
      title: string; 
      category: string;
     } 

ParentComponent显示第 1 页的帖子及其子项,ChildComponent显示第 1 页的帖子和category=book.

在任何时候,页面或类别可能会发生变化,或者可能会创建新帖子......

数据库很大,所以我无法将所有帖子加载到 Angular 应用程序中。

我有一个PostServiceGetByQuery 方法:

    class PostService {
      GetByQuery(category: string, page: number) : Observable<Post[]> {
        // implementation 
      }
    }

page如果orcategory更改或新post创建的,如何更新状态?

标签: angularreduxngrxangular9

解决方案


不幸的是,提供的信息是不够的,因为它没有显示你有哪些动作和减速器。

通常对于这样的事情,当我们需要做一些除了减少人们effects与他们一起使用的动作之外的事情时,您可以监听 的变化pagecategory或者新的post并导致另一个动作,例如reload数据。

在这里您可以找到所有信息:https ://ngrx.io/guide/effects

一个示例(它是带有装饰器的旧示例,目前应该使用 createEffect 函数)。

@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) {}
}

推荐阅读