Ngrx 最新更新提供了对 Angular 信号的支持。
我正在寻找一种方法来链接同步http调用。
首先我想到将它们直接链接到商店声明中。
但是我不知道如何做到这一点,也不知道这样做是否正确。
如果有人知道如何执行此类同步调用,我将不胜感激。
export const BookStore = signalStore(
{providedIn: 'root'},
withState(initialState),
withMethods((store, bookService = inject(BookService)) => ({
loadRandomAuthor: rxMethod<number>(
pipe(
switchMap(() => {
return bookService.getRandomAuthor().pipe(
tap({
next: (author: Author) => {
patchState(store, {author});
// 👉 call loadBooksByAuthorId method with author.id here
},
})
);
})
)
),
// 👉 here is the method to be synchronously called
loadBooksByAuthorId: rxMethod<number>(
pipe(
switchMap((authorId: number) => {
return bookService.getBooksByAuthorId(authorId).pipe(
tap({
next: (books: Book[]) => {
patchState(store, {books});
},
})
);
})
)
)
}))
);
HTTP 请求是异步的。你的意思是结果。
从一种效果调用另一种效果是一种代码味道。
我建议这样:
loadRandomAuthor()
应该在状态中设置authorId
,并且loadBooksByAuthorId()
应该在状态中观察authorId
并在该id更改时加载书籍。