使用 Ngrx 和信号进行链式同步 http 调用

问题描述 投票:0回答:1

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});
                            },
                        })
                    );
                })
            )
        )
    }))
);
angular rxjs signals ngrx
1个回答
0
投票

HTTP 请求是异步的。你的意思是结果。

从一种效果调用另一种效果是一种代码味道。

我建议这样:

loadRandomAuthor()
应该在状态中设置
authorId
,并且
loadBooksByAuthorId()
应该在状态中观察
authorId
并在该id更改时加载书籍。

© www.soinside.com 2019 - 2024. All rights reserved.