![](/img/trans.png)
[英]What is the difference between StoreModule.forRoot() and StoreModule.forFeature()
[英]How to access another modules store with ngrx's StoreModule.forRoot() and StoreModule.forFeature()
建立一个angular5 app ...与vue或反应相比,这么多移动部件,但我坚持使用它。
利用角度延迟加载模块我正在生成角度作为模块的每个页面。 每个模块都有自己的封装存储使用ngrx:
StoreModule.forFeature('home', HomeReducer),
到目前为止一直这么好..我们可以轻松地将数据注入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 {
}
该组件也很简单,看起来像这样:
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));
}
}
clickme
函数调度和动作,由效果监听,然后触发对成功的http请求的另一个动作,最终将数据放入视图中...
但现在显而易见的下一步......我需要与另一个页面共享此数据。 立即想到两个问题
1 - 从另一个模块访问一个模块存储数据的最佳方法是什么?
2 - 如果需要与另一个模块共享,那么封装模块数据的重点是什么,例如,登录模块将始终需要共享用户数据..只有使用这个forFeature()
才能获得数据的答案。真的只会被模块使用吗?
恕我直言:将状态拆分为模块是一个很好的意识形态,可用于可重用代码块的最终实践。 我的意思是编写一个自包含的模块,只需将其放入您的应用程序即可...但是应用程序几乎总是需要将数据从一个模块传递到下一个模块,并且当需要将这些模块发送到模块时会产生更多问题而不是解决。
您只需将HomeModule导入另一个模块,这样家庭功能的存储和效果也将在该新模块中注册。 之后,您需要在新模块组件的构造函数中定义主要功能的存储,并且您将能够像在HomeModule中一样使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.