我刚刚开始学习 ngrx 信号,令我震惊的一件事是“存储”文件可能会变得非常大,而且速度很快,所以理想情况下我想将其分成单独的部分。
下面是我如何拆分“withMethods”工厂的示例,但我无法确定
bookMethodsFactory
函数中“store”的类型应该是什么以及如何避免循环依赖?
import { inject } from '@angular/core';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
// book.model.ts
export interface Book {
id: number;
title: string;
}
// books.service.ts
export class BooksService {
public getBooks(): Promise<Book[]> {
return Promise.resolve([
{ id: 1, title: 'Book 1' },
{ id: 2, title: 'Book 2' },
{ id: 3, title: 'Book 3' }
]);
}
}
type BooksState = {
books: Book[];
};
// book
const initialState: BooksState = {
books: []
};
export const BooksStore = signalStore(
{ protectedState: false },
withState(initialState),
withMethods(bookMethodsFactory)
);
// book.methods.ts
export const bookMethodsFactory = ((store: ???) => {
const bookService = inject(BooksService);
return {
async loadBooks(): Promise<void> {
const books = await bookService.getBooks();
patchState(store, { books });
}
}
});
在 ngrx 信号存储中,您可以使用 signalStoreFeature 创建扩展。如果您有一长串 withMethods 函数,则可以在您的情况下使用它,或者您可以使用它在信号存储之间共享代码。
因此,在您的情况下,您可以创建一个单独的文件book.signalMethods.ts
export function withMySeparatedMethods() {
return signalStoreFeature(
withMethods((store, authService = inject(AuthService)) => {
//loadBooks
// function2
// function3
return { loadBooks, function2, function3 };
})
)
}
然后您需要做的就是将其导入到您的主信号存储中
export const BooksStore = signalStore(
{ protectedState: false },
withState(initialState),
withMySeparatedMethods() // HERE
);