亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

一個 NGRX 商店,多個 Angular 應用程序

一個 NGRX 商店,多個 Angular 應用程序

慕碼人2483693 2023-04-20 10:01:31
所以我對此有點不以為然。希望你能給我道歉。我正在嘗試將多個 Angular 元素(Web 組件)插入到 Prestashop 模塊,即 PHP。由于沒有一個包含許多模塊的 Angular 應用程序,我無法使用商店將數據從一個元素發送到另一個元素。我想過創建一個負責創建 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    }所以回顧一下,如果我想在多個獨立的角度應用程序之間共享狀態,你會怎么做?我嘗試使用 localStorage,添加事件以將 NGRX 狀態與本地存儲中的數據同步,反之亦然,但有時會出現無限循環,有時會出現數據不同步的邊緣情況。感謝您的幫助和理解
查看完整描述

1 回答

?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

所以現在,我找到了一種解決方法來避免商店的雙重實例化。使用條件注入器。


  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

    }

  }

我還沒有測試它在獨立應用程序之間共享數據。讓我們希望它有效。


隨時歡迎任何建議!


查看完整回答
反對 回復 2023-04-20
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號