简体   繁体   English

如何调用嵌套在控制器内的函数?

[英]How to call a function nested within within a promise from the controller?

This is my factory. 这是我的工厂。 I'm calling the promise from the factory, because I'm trying to keep my controllers as clean as possible, and the session information never really needs to be updated / put into $scope. 我正在从工厂发出承诺,因为我试图保持控制器尽可能整洁,并且会话信息永远不需要真正更新/放入$ scope中。 But, since it's async, how would I call getNextEvent (another async function) from the controller, and still have it be able to referrence the var sessionId? 但是,由于它是异步的,我将如何从控制器中调用getNextEvent(另一个异步函数),并且仍然能够引用var sessionId?

(function(){
    'use strict';

angular.module('csMgmtApp')
    .factory('agentFactory', ['$http', function($http){

        var result = {},
            data = {},
            access_token = result.access_token,
            baseURI = result.resource_server_base_uri;

        function startSession(startSessionPayload){
                access_token = result.access_token;
                baseURI = result.resource_server_base_uri;

            return $http({
                'url': baseURI + 'services/v6.0/agent-sessions',
                'method': 'POST',
                'headers': {'Authorization': 'bearer ' + access_token, 'content-Type': 'application/json'},
                'data': startSessionPayload
            }).then(function(res){
                 data.sessionId = res.data.sessionId;
                console.log("sessionId", data.sessionId);


 Want to call from controller --> function getNextEvent(timeout) {
                    $.ajax({
                        //The baseURI variable is created by the result.base_server_base_uri
                        //which is returned when getting a token and should be used to create the URL Base.
                        'url': baseURI + 'services/v6.0/agent-sessions/' + data.sessionId + '/get-next-event?timeout=' + timeout,
                        'type': 'GET',
                        'headers': {
                            //Use access_token previously retrieved from inContact token service
                            'Authorization': 'bearer ' + access_token,
                            'content-Type': 'application/x-www-form-urlencoded'
                        },
                        'success': function (result) {
                            //Process success actions
                            //Note the scenarios listed below are only a 
                        });
 });

    return {startSession:startSession}
        }]);
})();

here's the controller: 这是控制器:

csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', 'agentFactory', '$timeout', function ($scope, $http, $document, $resource, agentFactory, $timeout) {

$scope.agentStatePayload = {};
$scope.startSessionPayload = {
    'stationPhoneNumber': '2222222222',
    'inactivityTimeout': 0,
    'inactivityForceLogout': 'false'
};

$document.ready(function () {
    agentFactory.getToken();
});

agentFactory.startSession($scope.startSessionPayload);

}]);

One option could be to return a promise from startSession that will resolve with the sessionId . 一种选择是从startSession返回一个将由sessionId解析的promise。 This would allow you to call getNextevent from anywhere, and have the main client be aware of the current session. 这将允许您从任何地方调用getNextevent ,并使主要客户端知道当前会话。


//factory 

function startSession(startSessionPayload) { 
    return $http({
      'url': baseURI + 'services/v6.0/agent-sessions',
      'method': 'POST',
      'headers': {'Authorization': 'bearer ' + access_token, 'content-Type': 'application/json'},
      'data': startSessionPayload
    }).then(function(res){
      data.sessionId = res.data.sessionId;
      console.log("sessionId", data.sessionId);
      // should return promise (based on bluebird.js), not very
      // familiar with angular/jquery promises
      return data.sessionId;
    });
}

// Controller now gets sessionId and is responsible for calling next event

var sessionStartedPromise = agentFactory.startSession($scope.startSessionPayload);
sessionStartedPromise.then(function(sessionId) {
    getNextEvent(timeout, sessionId);
});

The above would make getNextEvent completely independent of the factory because it would take a sessionId. 上面的代码将使getNextEvent完全独立于工厂,因为它将使用sessionId。 I'm not sure of the specifics of factories in angular and how they are loaded across controllers, but this might make it so if you export getNextEvent it will still have access to data with the sessionId , not really sure though... 我不确定角度工厂的详细信息以及它们如何在控制器之间加载,但这可能会使它如此,因此如果您导出getNextEvent它仍然可以使用sessionId访问data ,尽管不确定...

Agent Factory Part 1 Define the startSession function 代理工厂第1部分定义startSession函数

angular.module('csMgmtApp')
    .factory('agentFactory', ['$http', function($http){
        var baseURI = "";         //from controller
        var accessToken = "";     //from controller
        var sessionId = "";       //from startSession POST
        var startResult = {};     //from startSession POST
        var startData = {};       //from startSession POST

        function startSession(startBaseURI, startAccessToken, startPayload){
            //save baseURI and accessToken
            baseURI = startBaseURI;
            accessToken = startAccessToken;

            var httpPromise = $http({
                'url': baseURI + 'services/v6.0/agent-sessions',
                'method': 'POST',
                'headers': {'Authorization': 'bearer ' + accessToken,
                            'content-Type': 'application/json'},
                'data': startPayload
            });

            var httpPromise2 = httpPromise.then( function(result) {
                 //save sessionId, result, data
                 sessionId = result.data.sessionId;
                 startResult = result;
                 startData = result.data;
                 //
                 return result;  //always return something
            });

            return httpPromise2; //always return something
        };

Agent Factory Part 2 Define the getNextEvent function 代理工厂第2部分定义getNextEvent函数

    function getNextEvent(timeout) {
        var httpPromise = $http({
            //use previously saved sessionID
            'url': baseURI + 'services/v6.0/agent-sessions/' + 
                   sessionId + '/get-next-event?timeout=' + timeout,
            'method': 'POST',
            'headers': {'Authorization': 'bearer ' + accessToken,
                        'content-Type': 'application/json'}
        });
        return httpPromise; //always return something
    };

    //always return something
    return { "startSession": startSession,
             "getNextEvent": getNextEvent
           };
}]);

Controller Use those functions to chain promises 控制器使用这些功能链接承诺

angular.module('csMgmtApp')
    .controller('launchedController', ['$scope','agentFactory',
                              function ($scope, agentFactory) {
    var vm = $scope;
    vm.baseURI = /* base URI here */ ;
    vm.accessToken = /* access token here */ ;
    vm.startPayload = {
        'stationPhoneNumber': '2222222222',
        'inactivityTimeout': 0,
        'inactivityForceLogout': 'false'
    };

    //get functions from agentFactory
    var startSession = agentFactory.startSession;
    var getNextEvent = agentFactory.getNextEvent;

    //Create start session promise
    var startSessionPromise = startSession(vm.baseURI,
                                           vm.accessToken,
                                           vm.startPayload);

    //Use startSessionPromise to create nextPromise
    var nextPromise = startSessionPromise.then( function (result) {
        vm.startData = result.data;
        vm.startDataReady = true;
        return getNextEvent(timeout); //call getNextEvent here
    });

    //Get data from nextPromise
    nextPromise.then( function (result) {
        vm.nextData = result.data;
        vm.nextDataReady = true;
    }) .catch ( function (error) {
        //process errors
    });
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM