我正在使用Angular 9和 "我的 "创建一个应用程序。NGRX 其中我有一个帖子类。
class Post {
id: number;
title: string;
category: string;
}
ParentComponent
显示第1页的帖子和它的子类。ChildComponent
显示第1页有以下内容的文章 category=book
.
在任何时候,页面或类别可能会发生变化,或者创建一个新的帖子......
数据库很大,所以我无法将所有帖子加载到Angular应用中。
我有一个 PostService
的方法GetByQuery来更新状态。
class PostService {
GetByQuery(category: string, page: number) : Observable<Post[]> {
// implementation
}
}
如何更新状态,如果 page
或 category
变化,或者如果有新的 post
创建?
不幸的是,所提供的信息是不够的,因为它没有显示你有哪些动作和减速器。
通常对于这样的事情,当我们需要做一些额外的事情,而不是减少一个动作时,人们会使用 effects
有了它们,你就可以聆听到 page
, category
或新 post
并引起另一个动作,如 reload
例如,数据。
在这里你可以找到所有信息。https:/ngrx.ioguideeffects。
一个例子(这是一个老的带有装饰器的例子,目前应该使用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) {}
}