Angular14中使用provideEffects()注册NgRx Effect遇类型错误
问题
在Angular 14项目中,在main.ts的providers数组中提供NgRx effect时,遇到如下错误:
Error: src/main.ts:18:21 - error TS2740: Type 'typeof import("/Users/macbook/IdeaProjects/angularPractice/src/app/auth/store/effects")' is missing the following properties from type 'Type<unknown>': apply, call, bind, prototype, and 5 more. 18 provideEffects([authEffects]),
相关代码如下:
effects.ts中的createEffect代码
export const registerEffect = createEffect( (actions$ = inject(Actions), authService = inject(AuthService), ) => { return actions$.pipe( ofType(authActions.register), switchMap(({ request }) => { return authService.register(request).pipe( map((currentUser: CurrentUserInterface) => { return authActions.registerSuccess({ currentUser }); }), catchError(() => { return of(authActions.registerFailure()); }), ); }), ); }, );
authActions代码
export const authActions = createActionGroup({ source: 'auth', events: { Register: props<{ request: RegisterRequestInterface }>(), 'Register success': props<{ currentUser: CurrentUserInterface }>(), 'Register failure': emptyProps(), }, });
authService代码
@Injectable({ providedIn: 'root', }) export class AuthService { constructor(private http: HttpClient) {} register(data: RegisterRequestInterface): Observable<CurrentUserInterface> { const url = environment.apiUrl + '/users'; return this.http .post<AuthResponseInterface>(url, data) .pipe(map((response) => response.user)); } }
main.ts中提供effect的代码
import { bootstrapApplication } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { AppComponent } from './app/app.component'; import { appRoutes } from './app/app.routes'; import { provideState, provideStore } from '@ngrx/store'; import { provideStoreDevtools } from '@ngrx/store-devtools'; import { importProvidersFrom, isDevMode } from '@angular/core'; import { authFeatureKey, authReducer } from './app/auth/store/reducer'; import { HttpClientModule } from '@angular/common/http'; import { provideEffects } from '@ngrx/effects'; import * as authEffects from './app/auth/store/effects'; bootstrapApplication(AppComponent, { providers: [ importProvidersFrom(HttpClientModule), provideRouter(appRoutes), provideStore(), provideEffects([authEffects]), provideState(authFeatureKey, authReducer), provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode(), autoPause: true, }), ], });
解决方向
- 错误核心是
provideEffects的传参方式错误:你当前传入的是整个authEffects模块对象,但该函数需要的是单个函数式effect实例,而非模块导出集合。 - 针对你现在用的NgRx 14+函数式effect,正确用法是直接传入导出的effect变量:
多个effect时,直接用逗号分隔传入:// main.ts中修改这一行 provideEffects(authEffects.registerEffect),provideEffects(authEffects.registerEffect, authEffects.loginEffect), - 确认NgRx版本与Angular 14匹配(NgRx 14对应Angular 14),版本不匹配会引发类型兼容问题。
- 检查effects.ts文件,确保
registerEffect被正确导出,无导出内容错误。
内容的提问来源于stack exchange,提问作者Sinmeister
相关产品推荐
相关产品推荐

