【问题标题】:AngularJS - self referencing services?AngularJS - 自引用服务?
【发布时间】:2014-01-25 18:10:44
【问题描述】:

我正在构建一个具有顶级控制器和二级控制器的 Angular 应用程序。将有 n 个二级控制器,但我想将全局级函数放在某个地方。我在服务中这样做。

我开始创建一个返回 api 的单一服务,实际上,它包含许多函数(如下)。该服务返回一个具有两个属性分支的对象,每个属性分支都包含一组函数。我如何从另一个调用其中一个?

globalModule.factory('global', function($http) {

    var squares = MyApp.squares;  // this is the *only* link from Global namespace to this app

    return {
        squareMgr: {
            getSquaresEarned: function() {
                return squares.earned;
            },
            getSquaresPlaced: function() {
                return squares.placed;
            },
            setThisSquareEarned: function(value) {
                squares.earned.push(value);
            },
            setThisSquarePlaced: function(value) {
                squares.placed.push(value);
            }
        },
        missionMgr: {
            missionInfo: {},
            setMissionInfo: function(missionInfo) {
                this.missionInfo = missionInfo
            },
            complete: function(missionData) {

                log('complete called on video at ' + new Date());
                missionData.complete = true;
                log(angular.toJson(missionData));

                $http({
                    url: '/show/completeMission',
                    method: "POST",
                    data: missionData 
                })
                .then(function(response) {
                    if (response.data.success === true) {

                        log('completeMission success');

                        // increment squares earned counter
                        this.squareMgr.setThisSquareEarned(missionData.id);

                        // above is an attempt to run a function contained in this 
                        // same service in a different parent property branch.
                        // how *should* I do this?
                    }
                });
            }
        }
    }
});

【问题讨论】:

  • 我会尝试在 return 语句之前创建 squareMgr 对象,然后在返回的对象中引用它。
  • 如果它们本质上是两个服务,为什么不明确说明并创建两个服务呢?然后可以将一个注入另一个。

标签: angularjs angularjs-service


【解决方案1】:

这样的事情怎么样:

globalModule.factory('global', function($http) {

    var glob = {
        squareMgr: {
           // ...
        },
        missionMgr: {
          foo: function() {
            glob.squareMgr.xyz(); 
          }

        }
    };

    return glob;
});

【讨论】:

  • 噢!我没想到。谢谢!
  • 我来寻找一种更“官方”的方式,但感谢您向我展示我没有以错误的方式这样做.. ;)
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多