如何使用ngrx的StoreModule.forRoot()和StoreModule.forFeature()访问另一个模块存储

Joh*_*ohn 5 ngrx ngrx-effects angular angular5

建立一个angular5应用...与vue或react相比,有这么多的活动部件,但我坚持使用它。

利用angulars的模块延迟加载我正在按角度生成每个页面作为模块。每个模块都有自己的使用ngrx封装的存储:

StoreModule.forFeature('home', HomeReducer),
Run Code Online (Sandbox Code Playgroud)

到目前为止一切顺利..我们可以轻松地将数据注入HomePages存储中,其模块看起来像这样:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';

import { HomeComponent } from './home.component';
import { HomeRoutingModule } from './home-routing.module';
import { HomeReducer } from '@modules/page/home/redux/home.reducers';
import { HomeEffects } from '@modules/page/home/redux/home.effects';
import { HomeService } from '@modules/page/home/home.service';

@NgModule({
  declarations: [
    HomeComponent
  ],
  imports: [
    CommonModule,
    HomeRoutingModule,
    StoreModule.forFeature('home', HomeReducer),
    EffectsModule.forFeature([HomeEffects])
  ],
  exports: [],
  providers: [
    HomeService
  ],
})

export class HomeModule {
}
Run Code Online (Sandbox Code Playgroud)

该组件也非常简单,如下所示:

import { Component, OnInit } from '@angular/core';
import * as homeActions from './redux/home.actions';
import { Store } from '@ngrx/store';
import { HomeState } from '@modules/page/home/redux/home.state';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-home-component',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  cars: Observable<any>;

  constructor (private store: Store<HomeState>) {
    this.cars = this.store.select(homeActions.getCars);
  }

  ngOnInit () {
  }

  clickme () {
    // dispatch a fetch to the store. gallery of images.
    // todo add a propper type model
    const imageType: any = {
      type: 'cars'
    };

    this.store.dispatch(new homeActions.GalleryFetch(imageType));
  }
}
Run Code Online (Sandbox Code Playgroud)

clickme函数将分派并执行动作,这些动作将被效果监听,依次触发成功的http请求上的另一个动作,最终将数据放入视图...

但是,现在显然是下一步了。我需要与另一页面共享此数据。马上想到两个问题

1-访问一个模块的最佳方法是从另一个模块存储数据?

2-如果需要与其他模块共享,则封装像这样的模块数据有什么意义,例如登录模块将始终需要共享用户数据..答案是仅将其forFeature()用于仅会用于被模块使用?

恕我直言:将状态分为模块是可重用代码块的最终实践的一种很好的意识形态。我的意思是编写一个自包含模块,然后将其简单地放入您的应用程序中是很棒的……但是一个应用程序几乎总是需要将数据从一个模块传递到下一个模块,而当这种情况需要发生时,将损坏的状态传递到模块中会带来更多问题比它能解决的要多。

小智 3

您只需将HomeModule导入到另一个模块中,这样主页功能的存储和效果也将注册到该新模块中。之后,您需要在新模块组件的构造函数中定义主页功能的存储,并且您将能够像在 HomeModule 中一样使用