我准备了一个带有后续输出的商店,并想制作一个页面作为作者的书籍,例如 localhost/history/author1
加载他们的书籍列表,即使我可以正确运行它,我也无法处理重定向到的错误路径另一个页面,因为它正在从状态读取数据并且必须首先加载它然后控制正确的路径输入。
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'history/:author', component: AuthorPageComponent },
{ path: 'not-found', component: NotFoundComponent },
{ path: '**', redirectTo: 'not-found' }
];
问题是 .subscribe
到 store$.select(BookSelectors.selectBookByAuthor, params.author)
首先返回空数组,如果我基于它运行导航,所有页面都重定向到主页,如果不根据我的 Routes 内容,任何 history/:author
请求将加载 AuthorPageComponent
那么我如何等待选择调用结束然后返回结果?
// console output during running select
Array [] author-page.component.ts:62:24
[WDS] Live Reloading enabled. client:52
Array [ {…}, {…} ] author-page.component.ts:60:24
// state output
ids: [...]
entities:
- id: 1
- title: 'test'
- author: {
- id: 0
- name: 'author1'
}
- id: 2
- title: 'example'
- author: {
- id: 0
- name: 'author1'
}
- id: 3
- title: 'sample'
- author: {
- id: 1
- name: 'author2'
}
// book.selector.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { Book } from '../../interfaces/book.interface';
import { BookState, bookAdapter } from './book.adapter';
export const selectBookState = createFeatureSelector<BookState>( 'books' );
export const {
selectIds,
selectEntities,
selectAll,
selectTotal
} = bookAdapter.getSelectors( selectBookState )
export const selectBookByAuthor = createSelector(
selectEntities,
(entities, author_name: string) => {
const books: Array<Book> = [];
if (entities) {
Object.values(entities).find(
(b) => {
if (b['author']['name'] === author_name) {
books.push(b as Book)
}
}
);
return books
}
}
)
对于作者页面为 author.component.ts
ngOnInit(): void {
this.route.params.subscribe(
(params: Params) => {
return this.store$.select(BookSelectors.selectBookByAuthor, params.author)
.subscribe(
result => {
if (result.length > 0) {
this.result = result
console.log(result)
} else { // the problem is here, first of all returns [] so navigates to home immediately
// this.router.navigate(['/']);
console.log(result)
}
}
)
}
)