我一直在寻找ngrx example-app并尝试使用以下内容扩展它:
做出这样的事情的正确方法是什么?
我添加了我的解决方案,它完成了工作,但我不确定它是否有用。在其中我将查询参数存储在两个看起来像反模式
的地方我的解决方案:
app / books / effects / books.ts中的在搜索效果中添加了路由器导航,这样无论何时触发搜索,都会使用查询字符串更新网址
search$: Observable<Action> = this.actions$.pipe(
ofType<Search>(BookActionTypes.Search),
debounceTime(this.debounce || 300, this.scheduler || async),
map(action => action.payload),
switchMap(query => {
if (query === '') {
return empty();
}
const nextSearch$ = this.actions$.pipe(
ofType(BookActionTypes.Search),
skip(1)
);
return this.googleBooks.searchBooks(query).pipe(
takeUntil(nextSearch$),
map((books: Book[]) => {
// added //
this.router.navigate([], {
queryParams: { query: query },
queryParamsHandling: 'merge',
});
///////////
return new SearchComplete(books);
}),
catchError(err => of(new SearchError(err)))
);
})
);
app / reducers / index.ts中的添加了路由器查询参数的选择器:
export const getRouterState = createFeatureSelector<
fromRouter.RouterReducerState<RouterStateUrl>
>('router');
export const getQueryParams = createSelector(
getRouterState,
state => state.state.queryParams
);
app / books / containers / find-book-page.ts中的添加了方法
urlQuery() {
// dispatch a search action if there is a query string in url
this.store
.pipe(select(fromRoot.getQueryParams), take(1))
.subscribe(queryParams => {
if (queryParams.query) {
this.search(queryParams.query);
}
});
}
此方法是从find-book-page组件中的构造函数调用的,因此当加载此组件时,它将检查url中是否存在查询字符串,如果是,则使用该查询字符串调度操作< / p>
constructor(private store: Store<fromBooks.State>) {
this.searchQuery$ = store.pipe(select(fromBooks.getSearchQuery), take(1));
this.books$ = store.pipe(select(fromBooks.getSearchResults));
this.loading$ = store.pipe(select(fromBooks.getSearchLoading));
this.error$ = store.pipe(select(fromBooks.getSearchError));
this.urlQuery();
}