Angular Service在返回promise时抛出异常

时间:2014-10-09 16:16:42

标签: javascript angularjs angular-promise

在我的app.js代码中,我正在运行一些从服务器中提取会话变量的初始化代码。

到目前为止很好;但是我现在正在尝试添加一个额外的调用来为树视图小部件提取数据。这个新调用导致JavaScript异常:

  "Cannot read property 'then' of undefined"

启动代码为:

1) app.run gets called first,

2) call into 'userService' to init various $rootScope vars

3) userService makes API calls to a server and returns data. $q.defer() and $http is used

**后续步骤导致异常

4) call into userService.getUserReportsTreeFromDataContext() from app.run

5) userService.getUserReportsTreeFromDataContext then calls down into datacontext.js (THIS SOMEHOW CAUSES AN EXCEPTION).

这是app.so

中的app.run()代码
app.run(['$route', '$rootScope', 'common', 'userService', function ($route, $rootScope, common, userService) {
 // initialize session vars     
   userService.openUserSession(razorEnvJson).then(function (data) {
            var sessionID = data.data[0];
            $rootScope.rageSessionVars.sessionID = sessionID;

            // **** THROWS EXCEPTION HERE ****                     
            userService.getUserReportsTreeFromDataContext().then(function (data){
                       // var myData = data;   
            });
    });
 }]);    

以及来自userContext.js服务的片段:

 this.openUserSession = function (razorEnvParams) {
        _razorEnvParams = razorEnvParams;

        _// some vars ommitted here for brevity
        var url = "http://" + _domain + ":" + _port + controllerpath + "?userid=" + user + "&pass=" + pass;
        var deferred = $q.defer();
        deferred.notify("Opening user session...");
        var retval = [];
        $http({
            method: 'GET',
            encoding: 'JSON',
            headers: {
                'Access-Control-Allow-Origin': 'true',
                'Content-Type': 'application/json'
            },
            withCredentials: true,
            url: url
        }).success(function (data, status, headers, config) {
            retval = data;
            deferred.resolve(retval);
        }).error(function (data, status, headers, config) {
            log("Cannot open a user session via api call. Errors details: " + data);
        });
        return deferred.promise;
    }

    this.getUserReportsTreeFromDataContext = function (userID) {         
        datacontext.getReportsTree().then(function (data) {
             return data;
        });            
    }

和我的datacontext.js代码从服务器提取数据,或者提取一些测试数据:

   (function () {
'use strict';

var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['$http', '$rootScope', 'common', datacontext]);

function datacontext($http, $rootScope, common) {
    var $q = common.$q;

     var service = {
        getReportsTree: getReportsTree,
        sendAggrRequestToServer: sendAggrRequestToServer,            
    };

    return service;

    function getReportsTree() {
        var reportsJson = [
            {
              id: 1, text: "Standard", expanded: false, spriteCssClass: "rootfolder", checkChildren: true, items: [ 
            { id: 3, text: "MTM Aggr", reptName: "MTM Aggr" },
            { id: 4, text: "Member Aggr", reptName: "Member Aggr"                }                                
        ]
},
{
    id: 30, text: "Hierarchy", expanded: false, spriteCssClass: "rootfolder", checkChildren: true, items: [
        { id: 31, text: "Ctpy Hrchy", reptName: "CTPYHIER", withHierarchy: 'true' },
        { id: 32, text: "Ctpy/BkgLocation Hrchy", reptName: "CTPYHIER_BKG_LOC", withHierarchy: 'true' }
    ]
}                          
];
        return $q.when(reportsJson);
    }
  })();  // end datacontext.js

仅供参考 - 我从dashboard.js控制器拨打许多其他成功的电话到datacontext.js没有任何问题。

这是一个很好的例子,其中一些测试数据来自datacontext:

dashboard.js -

    function getPositionsData() {
        datacontext.getPositions().then(function (data) {
            vm.positionsData = data;
            populateGridDataSource(vm.positionsData);
        });
    }

datacontext.js -

   function getPositions() {
        var positionsJson = [
            { id: 1, product: "BAX", instrument: "BOND-0003", position: 11, delta: 0.02, gamma: 0.79, initMarin: 600, initMarginPctChange: 250, varMargin: 75 },
            { id: 2, product: "BAX", instrument: "BOND-0004", position: -4, delta: 0.12, gamma: 0.46, initMarin: 400, initMarginPctChange: 300, varMargin: 65 },
            { id: 3, product: "BAX", instrument: "BOND-0004", position: 9, delta: 0.09, gamma: 0.55, initMarin: 700, initMarginPctChange: 200, varMargin: 40 }
        ];
        return $q.when(positionsJson);
    }

1 个答案:

答案 0 :(得分:1)

您忘记在getUserReportsTreeFromDataContext函数中返回您的初始承诺:应该是这样的:

this.getUserReportsTreeFromDataContext = function (userID) 
{ return datacontext.getReportsTree()
         .then(function (data) { return data; }); 
}