【问题标题】:NgRx Store doesn't get values when components are from different modules - Angular当组件来自不同的模块时,NgRx Store 不会获取值 - Angular
【发布时间】:2019-10-25 10:34:05
【问题描述】:

我正在开发一个具有以下模块结构的 Angular 应用程序。

app.module.ts 在这个模块中,我还有两个模块,分别称为 home.module.tsadmin.module.ts

我在我的应用程序中使用 NgRx 进行状态管理。我想要做的是,当home.module.ts 中的某个组件上发生某些事件时,这里调度的操作应该反映在app.module.ts 甚至兄弟模块admin.module.ts 中。动作分派在同一模块的两个组件之间完美运行(无论父子关系或子父关系),但在模块更改时却不行。

StoreModule 已经包含在app.module.ts 中,我在home.module.ts 中导入了它,但仍然没有成功。

我需要有关此问题的帮助,谢谢。

另外,请注意,商店在同一模块的组件中完美运行。即动作被分派,甚至其他组件同时监听它。

调度操作的组件 1

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store'
import { Test } from '../../../ngrx/models/test.model'
import * as TestActions from '../../../ngrx/actions/test.actions'

@Component({
  selector: 'app-add-test',
  templateUrl: './add-test.component.html',
  styleUrls: ['./add-test.component.css']
})
export class AddTestComponent implements OnInit {

  constructor(
    public store: Store<Test[]>
  ) { }

  ngOnInit() {
  }

  addDataToStore(){
    console.log("Action Dispatched... [Add Test]")
    const data = {
      name : "Adnan Khan",
      email : "adnan@khan.com"
    }
    this.store.dispatch(new TestActions.TestAdd(data))
  }

}

显示数据的组件 2

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs'
import { Store } from '@ngrx/store'
import { Test } from '../../../ngrx/models/test.model'

@Component({
  selector: 'app-show-test',
  templateUrl: './show-test.component.html',
  styleUrls: ['./show-test.component.css']
})
export class ShowTestComponent implements OnInit {

  constructor(
    public store: Store<Test>
  ) { }

  storeData: Observable<Test[]>

  ngOnInit() {
    this.storeData = this.store.select('test')
  }

}

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    一个被调度的动作将被传递给每个注册的reducer。 如果模块 A 调度了一个动作,模块 B 中的减速器将接收调度的动作。 唯一的必要条件是模块 B 已加载。

    更多信息Sharing data between modules is peanuts

    【讨论】:

    • 是的,模块 B 也加载了,但仍然无法工作
    • 如果你能重现,我很乐意看看。
    猜你喜欢
    • 2019-09-23
    • 2023-03-22
    • 2018-12-04
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2018-02-12
    相关资源
    最近更新 更多