角圆依赖性解决方案 [英] angular circular dependency work-around

查看:77
本文介绍了角圆依赖性解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小提琴: https://jsfiddle.net/ahmadabdul3/L3eeeh6n/

我正在构建一个应用程序.这个应用程序以一些我可以添加到其中的静态数据开始.我遇到的问题(循环依赖)来自于此初始静态数据.这是场景:

I'm building an app. This app starts with some static data that I can add to, remove from. The problem I'm having (circular dependency) comes from this initial static data. Here's the scenario:

我有2种服务(水果,篮子).每个水果只能属于一个篮子,但是每个篮子可以容纳许多水果.这两个服务(如下)相互依赖:

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

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

它们相互依赖的原因是因为我拥有初始静态数据:

the reason they depend on each other is because of the initial 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
     }
   }
  ];
}

如您所见,我有一个函数 basket 返回一个篮子项目,这样我就可以从水果对象中动态检索篮子对象.

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

篮子服务类似:

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

与fruitService一样,我有一个 fruits 函数,可以在我请求水果对象时给我它们.我尝试了各种方法的组合来尝试分解实际的静态数据和服务,以克服这种循环依赖关系,但是这种情况并没有发生.

same as the fruitService, I have a fruits function that can give me fruit objects when I ask for them. I've tried different combinations of ways to try to break apart the actual static data and the service to overcome this circular dependency, but its not happening.

如何在没有这种循环依赖的情况下构建

how can I architect this without having this circular dependency

推荐答案

其中一项服务使用$ injector并在运行时对服务进行查找

Have one of the services use $injector and do a lookup for the service at runtime

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

您需要在服务参数中添加$ injector,以使其正常工作(以防万一有任何问题)

You will need to add $injector to your service parameters for this to work (just in case there was any question)

这篇关于角圆依赖性解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆