You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ng-packagr时出现NullInjectorError: No provider for StateObservable求助

解决Angular 5 + NgRx Store 共享库编译后依赖注入错误的问题

嘿,我之前也碰到过几乎一模一样的问题!这个NullInjectorError: No provider for StateObservable!本质是重复加载了@ngrx/store模块——当你用ng-packagr编译共享库再通过yarn link引入主应用时,主应用和共享库各自拥有一份独立的@ngrx/store代码副本,导致Angular的依赖注入系统没法识别跨副本的服务实例,自然找不到需要的StateObservable。

下面是具体的解决步骤,亲测有效:

1. 把共享库的@ngrx/store设为peer依赖

打开共享库的package.json,把@ngrx/store从dependencies移到peerDependencies里,这样共享库就不会自己打包ngrx,而是依赖主应用提供的版本:

{
  "peerDependencies": {
    "@ngrx/store": "^5.2.0",
    "@angular/core": "^5.2.0",
    // 其他你需要的peer依赖也一起放这里
  }
}

2. 重新编译共享库

先删掉共享库的dist目录,再重新执行编译命令:

ng-packagr -p ng-package.json

3. 解决yarn link导致的依赖重复问题

yarn link会让共享库优先用自己node_modules里的依赖,所以得强制它用主应用的@ngrx/store:

  • 进入主应用根目录,执行:
    yarn link "../path-to-your-shared-library/node_modules/@ngrx/store"
    
    或者更省心的方式,在主应用的package.json里加个resolutions字段(仅限yarn):
    {
      "resolutions": {
        "@ngrx/store": "^5.2.0"
      }
    }
    
    加完后重新跑yarn install,确保整个项目只有一份@ngrx/store的副本。

4. 检查主应用的StoreModule配置

再确认下你的AppModule里的导入没问题,别重复导入:

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { reducers } from './reducers';

@NgModule({
  imports: [
    StoreModule.forRoot(reducers)
  ]
})
export class AppModule { }

额外小提示

  • 把主应用和共享库的node_modules、dist都清一遍,重新装依赖编译,避免缓存搞事情。
  • 共享库里面别用StoreModule.forRoot(),应该用StoreModule.forFeature()来注册特性reducer,forRoot只在主应用的AppModule里用一次就够了。

内容的提问来源于stack exchange,提问作者Joe Attardi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:46:52