簡體   English   中英

如何使用ngrx的StoreModule.forRoot()和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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM