Angular/NgRx使用createFeature时出现‘Cannot find name 'on'’编译错误
解决NgRx createFeature中“Cannot find name 'on'”编译错误
问题原因
on 是NgRx Store库提供的核心工具函数,用于在reducer中绑定action与状态更新逻辑。出现该错误的核心原因是未从@ngrx/store中导入on函数。
解决方案
在你的reducer文件顶部添加以下导入语句:
import { createFeature, createReducer, on } from '@ngrx/store';
修改后的完整代码示例:
import { createFeature, createReducer, on } from '@ngrx/store'; // 确保导入对应的action import * as BookListPageActions from './book-list-page.actions'; import * as BooksApiActions from './books-api.actions'; // 定义initialState(假设你已完成该定义) const initialState = { books: [], loading: false }; export const booksFeature = createFeature({ name: 'books', reducer: createReducer( initialState, on(BookListPageActions.enter, (state) => ({ ...state, loading: true, })), on(BooksApiActions.loadBooksSuccess, (state, { books }) => ({ ...state, books, loading: false, })) ), });
额外排查点
- 确认
@ngrx/store版本(当前为14.3.2)与Angular版本(14.2.0)兼容:两者大版本匹配,不存在兼容冲突。 - 检查导入语句是否存在拼写错误,比如误导入到
@ngrx/store-devtools或其他NgRx子包。
内容的提问来源于stack exchange,提问作者grx00
相关产品推荐
相关产品推荐

