一个NGRX商店,多个Angular应用程序

时间:2020-10-05 18:32:46

标签: javascript angular ngrx store ngrx-store

所以我对此有点怀疑。希望你能向我道歉。

我正在尝试将多个Angular元素(Web组件)插入到PHP的Prestashop模块中。由于没有一个带有多个模块的Angular App,所以我无法使用存储将数据从一个元素发送到另一个元素。

我已经考虑过创建一个负责创建NGRX存储的库,并将其保存到window.store中(例如),这样同一存储可以被多个独立的角度应用程序使用。这里的问题是我必须在许多Angular元素中调用该库,所以我在构造函数中注入了不同的存储。我说的对吗?

例如:

import {
  ActionReducer,
  ActionReducerFactory,
  ActionReducerMap,
  ActionReducerMap,
  ActionsSubject,
  ReducerManager,
  ReducerManagerDispatcher,
  StateObservable,
  Store,
} from '@ngrx/store'
import { Observable } from 'rxjs';

const storeName = 'store'

@Injectable({
  providedIn: 'root'
})
export class StoreSyncService {

  store: any = null

  // option 1 constructor:
  // are we, when including the library in others angular apps, instantiating store over and over?
  constructor(private store: Store) {
     if (window[storeName]) {
      this.store = window[storeName]
    } else{
      window[storeName] = this.store
    }
  }

  // option 2 constructor (please apologise me as I don't know how injection works very well).
  // Any link to clarify this is welcome
  constructor() {
    if (window[storeName]) {
      this.store = window[storeName]
    } else{
      const stateObservable$: StateObservable = new Observable()
      const actionsObserver: ActionsSubject = new ActionsSubject()

      const dispatcher: ReducerManagerDispatcher = new ActionsSubject()
      const initialState = {}
      const reducers: ActionReducerMap<any, any> = {}
      const reducerFactory: ActionReducerFactory<any, any> =  whatever

      const reducerManager: ReducerManager = new ReducerManager(dispatcher, initialState, reducers, reducerFactory)
      this.store = new Store(stateObservable$, actionsObserver, reducerManager)
      window[storeName] = this.store
    }
  }

  public getStore = () => this.store

  public addReducer = (reducerName: string, reducer: ActionReducer<any>) => this.store.addReducer(reducerName, reducer)

  public removeReducer = (reducerName: string) => this.store.removeReducer(reducerName)

}

回顾一下,如果我想在多个独立的角度应用之间共享状态,你会怎么做?

我尝试使用localStorage,添加了一些事件以使NGRX状态与本地存储中的数据同步,反之亦然,但结果有时是无限循环,有时甚至是数据不同步的边缘情况。

感谢您的帮助和理解

1 个答案:

答案 0 :(得分:0)

因此,就目前而言,我已经找到一种解决方法来避免商店的双重实例化。使用条件注射器。

  import { Injectable, Injector } from '@angular/core';

  ...


  constructor(private injector : Injector) {
    if (window[storeName]) {
      this.store = window[storeName]
    } else{
      this.store = this.injector.get<Store>(Store);
      window[storeName] = this.store
    }
  }

我仍然没有测试它在独立应用程序之间共享数据。希望它能起作用。

总是欢迎任何建议!