Angular 16中使用NgRX出现No overload matches this call错误求助
问题排查与解决:Angular 16 + NgRX store.select() 类型错误
错误信息
/mypage.component.ts:29:42 - error TS2769: No overload matches this call. Overload 1 of 9, '(mapFn: (state: object) => unknown): Observable<unknown>', gave the following error. Argument of type 'string' is not assignable to parameter of type '(state: object) => unknown'. Overload 2 of 9, '(key: never): Observable<never>', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'. entry_one = this.store.select('selectEntryOne') ~~~~~~~~~~~~~
核心错误原因
- 组件中错误地将字符串字面量
'selectEntryOne'传给store.select(),但该方法需要接收的是NgRX创建的选择器函数(即data.selectors.ts中定义的selectEntryOne),而非选择器名称字符串。 - 组件属性声明语法错误:
entry_one: this.store.select(...)是错误写法,应使用赋值语法,同时建议显式声明变量类型。
组件代码修正(mypage.component.ts)
import { Component } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { selectEntryOne, selectEntryTwo } from '@state/selectors/data.selectors'; import { Data } from '@models/data'; @Component({ selector: 'app-mypage', template: `<div>Entry One: {{ entry_one$ | async }}</div> <div>Entry Two: {{ entry_two$ | async }}</div>` }) export class MyPageComponent { // 用$后缀区分Observable(NgRX最佳实践),显式声明类型 entry_one$: Observable<any> = this.store.select(selectEntryOne); entry_two$: Observable<any> = this.store.select(selectEntryTwo); constructor(private store: Store) { } }
修正点说明
- 直接传入导入的选择器函数
selectEntryOne,替代字符串参数 - 补充缺失的
@Component装饰器(Angular组件必须具备该装饰器) - 给Observable变量添加
$后缀,便于区分普通变量与可观察对象 - 显式声明变量类型为
Observable<any>,若需更严格类型,可替换为Observable<Data['entry_one']>
其他潜在问题修正
1. Reducer中的Action导入错误
data.reducers.ts中导入的Action与实际使用不符,修正如下:
// 原代码 import { setData } from '@state/actions/data.actions' // 修正后 import { setEntryOne, setEntryTwo } from '@state/actions/data.actions'
2. Reducer语法错误(缺失闭合括号)
data.reducers.ts的createReducer缺少闭合括号,导致语法错误:
export const dataReducer = createReducer( initialState, on(setEntryOne, (state, { data }) => ({ ...state, data: { ...state.data, entry_one: data.entry_one }, })), on(setEntryTwo, (state, { data }) => ({ ...state, data: { ...state.data, entry_two: data.entry_two }, })) ); // 补充该闭合括号
3. 确保AppState类型定义正确
app.state.ts需正确定义根状态,包含对应DataState的data属性:
import { DataState } from './reducers/data.reducers'; export interface AppState { data: DataState; }
模板中使用Observable
需通过async管道订阅Observable并获取值,避免手动订阅引发内存泄漏:
<div>Entry One: {{ entry_one$ | async }}</div> <div>Entry Two: {{ entry_two$ | async }}</div>
内容的提问来源于stack exchange,提问作者Scottish Smile
相关产品推荐
相关产品推荐

