Angular circular dependency

script: https://jsfiddle.net/ahmadabdul3/L3eeeh6n/

I am creating an application. This application starts with some static data that I can add, remove from. The problem I encountered (circular dependency) arises from this initial static data. Here's the script:

I have 2 services (fruit, basket). Each fruit can belong to only one basket, but each basket can contain many fruits. These two services (below) depend on each other:

function fruitService() {} function basketService() {} 

the reason why they depend on each other is related to the original static data that I have:

 function fruitService(basketService) { var data = [ { id: 0, name: 'apple', basket: function() { return basketService.getById(this.refs.basket); }, refs: { basket: 0 } } ]; } 

as you can see, I have a basket function that returns a basket element so that I can dynamically retrieve basket objects from fruit objects.

The basket service is similar:

 function basketService(fruitService) { var data = [ { id: 0, name: 'basket1', fruits: function() { return fruitService.getByIdList(this.refs.fruits); }, refs: { fruits: [0, ...] } } ]; } 

the same as fruitService, I have a fruits function that can give me fruit objects when I ask for them. I tried different combinations of ways to try to break the actual static data and the service to overcome this cyclical dependency, but it does not happen.

how can i archive this without this circular dependency

0
source share
3 answers

If one of the services uses $ injector and searches for the service at runtime

 var injectedService = $injector.get('servicenamehere'); 

You will need to add the $ injector to your service settings for this to work (just in case you have any questions)

+1
source

You do not need 2 services. I think that is enough.

 function basketService() { var data = [ { id: 0, name: 'apple', basketName: 'basket1' }, ]; var service = { getFruitById: getFruitById, getBasketById: getBasketById }; function getFruitById(fruitId){ // return one fruit here } function getBasketById(basketId){ // return your basket with a list of fruits } } 
+1
source

Another option would be to use a constant to store your data.

 angular.module('yourApp').Constant("fruitAndBasketConstant", { baskets : [{ id : 0, fruits : [ { // some info }, { // some info } ] }] }); 

And create a service that will request your constant.

 angular.module("yourApp").factory("FruitService"["fruitAndBasketConstant", function(fruitAndBasketConstant){ var service = { getFruitById: getFruitById }; return service; function getFruitById(fruitId){ // loop through fruitAndBasketConstant.baskets // and return the fruit you want } }]); 

And do the same for your basket.

0
source

Source: https://habr.com/ru/post/1013831/


All Articles