【问题标题】:In Angular 6 I get the error "NullInjectorError: No provider for Store" in a component在 Angular 6 中,我在组件中收到错误“NullInjectorError: No provider for Store”
【发布时间】:2019-04-20 03:51:42
【问题描述】:

这个简化的组件调度一个动作来将数据保存到商店:

import { Store } from '@ngxs/store';
import { ViewLogin } from '../actions/login.actions';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})

export class NavbarComponent {
  constructor(private store: Store) {}

  onSignInClick(login: string) {
    this.store.dispatch(new ViewLogin({ login }));
  }
}

它总是带来错误NullInjectorError: No provider for Store!

奇怪的是,我在应用程序的另一个组件中拥有相同的代码,而且它运行起来没有任何问题!

有什么想法吗?

【问题讨论】:

  • 您需要确保 Store 已添加到模块的 providers 数组中。确保该模块是声明 NavbarComponent 的模块,或者是 AppModule 等父模块
  • @user184994 谢谢!我以前做过,但忘记了这部分xD

标签: angular dependency-injection store ngxs


【解决方案1】:

使用 NGXS,您无需将 Store 作为提供程序直接注入,而是将 NgxsModule 导入根 AppModule

来自文档:

import { NgModule } from '@angular/core';
import { NgxsModule } from '@ngxs/store';

@NgModule({
  imports: [
    NgxsModule.forRoot([
      ZooState
    ])
  ]
})
export class AppModule {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2022-12-27
    • 2021-10-16
    • 2018-10-14
    • 2018-08-27
    • 2019-04-03
    • 2021-03-09
    相关资源
    最近更新 更多