redux-observable,为依赖项注入依赖项

时间:2017-11-05 21:22:16

标签: dependency-injection redux-observable

我正在使用redux-observable并且有两个依赖项。第二个依赖性也取决于第一个依赖性。

StoreService依赖于ConfigService,这是StoreService的类

const StoreService = (http, Config) => {
    return {
        getStores: () => {
            const syncGalaxyStoresUrl = Config.syncGalaxyUrl + Config.storesEndPoint;
            return Observable.fromPromise(axios.get(syncGalaxyStoresUrl));
        }
    };
};

这是我声明我的依赖

的方式
const epicMiddleware = createEpicMiddleware(rootEpic, {
    dependencies: {
        http: axios,
        Config: configParams,            
        StoreService: StoreService,
    }
});

如何将第二个依赖项Config和http注入StoreService依赖项?

1 个答案:

答案 0 :(得分:0)

听起来像关闭会起作用

const epicMiddleware = createEpicMiddleware(rootEpic, {
  dependencies: {
      http: axios,
      Config: configParams,            
      StoreService: () => StoreService(axios, Config),
  }
});

另一种方法是利用StoreService是一个本身在闭包中捕获它们的工厂的事实。然后在你的史诗中你不必做StoreService().getStores(),他们可以做storeService.getStores()

const createStoreService = (http, Config) => {
  return {
      getStores: () => {
          const syncGalaxyStoresUrl = Config.syncGalaxyUrl + Config.storesEndPoint;
          return Observable.fromPromise(axios.get(syncGalaxyStoresUrl));
      }
  };
};

const epicMiddleware = createEpicMiddleware(rootEpic, {
  dependencies: {
      http: axios,
      Config: configParams,            
      storeService: createStoreService(axios, Config)
  }
});