试图让间隔功能与我的工厂一起工作

时间:2015-08-14 13:53:26

标签: javascript angularjs

我创建了一个工厂,我将我的http请求添加,检索和删除任务。

现在,当我添加任务时,你看不到视觉上的变化。我必须刷新浏览器。现在要解决这个问题,我想我会编写一个函数来检查旧数组的长度与新数组的长度,并在其上设置一个间隔1分钟以进行此更改然后拉入任务。我能够记录数组的长度变化,但没有任何东西在视觉上发生(仍然需要刷新浏览器)。

如果有人可以帮助我。

我app.js代码的一部分:

全球变量 - > defaultStart,defaultEnd,clickDate

zazzleApp.factory('TaskService', function ($http) {
    var TaskService = {};

    TaskService.taskList = [];

    TaskService.getTasks = function(cb){
        $http.get('api/task/all')
            .success(function(dataFromServer){

                for (var i = 0; i < dataFromServer.length; i++) {
                    TaskService.taskList[i] = dataFromServer[i];
                };

                //console.log('LOGGING GET_TASK ',  TaskService.taskList);
                if(cb){
                    cb(dataFromServer);
                }else{
                    return dataFromServer;
                }

                //return dataFromServer;

            })
            .error(function(errorFromServer){
            //something went wrong, process the error here
                console.log("Error in getting the users from the server ", errorFromServer);
            })
    };

    TaskService.addTask = function(pTask){
        var newClickDate = clickDate;
        console.log('LOGGGING NEW CLICK DATE = ', newClickDate);

        var newEditId = editId;
        //console.log('LOGGGING NEW edit id = ', newEditId);
        var url;

        if (newEditId) {
            url = 'api/task/update/' + newEditId;
        } else {
            url = 'api/task/create';
        }

        //console.log("URL URL USA", url, newEditId, newClickDate);

        defaultStart = new Date(newClickDate);
        defaultStart = defaultStart.getFullYear() + "-" + (defaultStart.getMonth() + 1) + "-" + defaultStart.getDate();
        defaultStart += " 00:00:00";

        defaultEnd = new Date(newClickDate).addDays(1);
        defaultEnd = defaultEnd.getFullYear() + "-" + (defaultEnd.getMonth() + 1) + "-" + defaultEnd.getDate();
        defaultEnd += " 00:00:00";

        console.log('LOGGING DEFAULT START AND DEFAULT END ' , defaultStart, defaultEnd);

        pTask.color = $('#containerColorPicker').attr('ng-data-id');

        // returns makes sure the promis is returned from the server
        return $http.post(url, {
            'name': pTask.project_name,
            'project_id': pTask.project_type,
            'location_id': pTask.location,
            'estimate_time': pTask.estimate_time || 2,
            'project_client_name': pTask.project_client_name,
            'url': pTask.url,
            'resource_link': pTask.resource_link,
            'notes': pTask.notes,
            'start_time': pTask.start_time || defaultStart,
            'end_time': pTask.end_time || defaultEnd,
            /*'start_time': defaultStart,
            'end_time': defaultEnd,*/
            'color': pTask.color
        }, {
            headers: {
                "Content-Type": "text/plain"
            }
        })
        .success(function(data, status, headers, config) {
                console.log(data);
                TaskService.getTasks();
                TaskService.taskList.push(data);//pushing the new task
                //console.log("YYYYYYYYYYYYY -------->>>>>", defaultStart);
        })
        .error(function(data, status, headers, config) {
            console.log("Failed to add the task to DB");
        });
    };

    TaskService.deleteTask = function (){
        var newEditId= editId;
        $http.delete('api/task/delete/' + newEditId)
            .success(function(dataFromServer){

                console.log('logging edit id in delete taks func server ', newEditId);

                var index;

                for (var i = 0; i < TaskService.taskList.length; i++) {
                    if(TaskService.taskList[i]._id == newEditId){
                        //index = i;
                        console.log ("removing the element from the array, index: ", newEditId, i);
                        TaskService.taskList.splice(i,1);
                    }
                };
                /*  if(editId !== -1){
                    console.log ("removing the element from the array, index: ", editId, index);
                    UserService.userList.splice(index,1);
                }*/

                console.log('TaskArray ', TaskService.taskList)
                $('div[ng-data-id="'+ newEditId +'"]').remove();

            })
            .error(function(errorFromServer){
                //something went wrong, process the error here
                console.log("Error in deleting a user from the server");
            })
    };

    return TaskService;
})


//START CONTROLLER
angular.module('zazzleToolPlannerApp')
    .controller('CalendarCtrl', function ($scope, $mdDialog, $http, $rootScope, $timeout, User, Auth, UserService, TaskService) {

    $scope.newTask = {};
    $scope.newTask.project_name = "";
    $scope.newTask.project_type = "";
    $scope.newTask.location = "";
    $scope.newTask.estimate_time = "";
    $scope.newTask.project_client_name = "";
    $scope.newTask.url = "";
    $scope.newTask.resource_link = "";
    $scope.newTask.notes = "";
    $scope.newTask.color = "";

    $scope.tasks = TaskService.taskList;

    $scope.getTasksFromService = function () {
        TaskService.getTasks(); //after this gets called, the data will be shown in the page automatically
    }
    $scope.getTasksFromService();

    $scope.addTaskWithService = function () {
        //note that you can process the promise right here (because of the return $http in the service)
        TaskService.addTask($scope.newTask)
            .success(function(data){
                //here you can process the data or format it or do whatever you want with it
                console.log("Controller: the task has been added");
                $scope.tasks = [];// EMPTY THE ARRAY
                $scope.tasks = TaskService.getTasks();
                //console.log('Taskservice Controller ', $scope.updateGridDataAwesome);
            })
            .error(function(data){
                //something went wrong
                console.log("Controller: error in adding task");
            });
    }

    $scope.deleteTaskWithService = function(){
        TaskService.deleteTask();
    }

TaskService.getTasks(function(data){
    $scope.tasks = data;
});

var interval = setInterval(function(){
    var oldLength = $scope.tasks.length;
    TaskService.getTasks(function(data){
        console.log('lengths', oldLength, data.length)
        if(oldLength != data.length){
            //$scope.tasks = data; 
            //TaskService.taskList.push(data);
            $scope.tasks = TaskService.getTasks();

        }
    });
}, 6000)

3 个答案:

答案 0 :(得分:0)

这可能是您正在寻找的,使用$interval您可以每x秒设置一个间隔:

$interval(function() {
  // Something to be executed after 1min (60000ms)
}, 60000);

然后将$interval注入您的工厂:

zazzleApp.factory('TaskService', function ($http, $interval).....

答案 1 :(得分:0)

试试这个:

$http
    .post("/api/pin", {})
    .success(function(data) {
        $scope.$apply(function() {
            $scope.pins.push(data);
        });
    });

参考:https://stackoverflow.com/a/24836089/3330947

更新

我是这样做的:

服务(获取所有帐户):

.factory('accountService', function ($http) {
        var accountObj = {
            async: function () {
                var promise = $http.get('account/').then(function (response) {
                    return response;
                });
                return promise;
            }
        };
        return accountObj;
    })

控制器:

//Call get accounts service and put all accounts in $scope.accounts
    var getAccounts = function () {
        accountService.async().then(function (d) {
            $scope.accounts = d.data;}
    }
//Create new account and update array of accounts
    $scope.createAccount = function () {
        $scope.data = {
                'id' : 0,
                'customerId' : $scope.outputCustomer[0].id,
                'camsId' : $scope.outputCams[0].id,
                'camsPin' : parseInt($scope.camsPin),
                'username' : $scope.username,
                'password' : $scope.password,
                'email' : $scope.email,
                'acfUsername' : $scope.acfUsername,
                'accountActive' : $scope.accountActive,
                'agentId' : $scope.outputAgent[0].id,
                'freeswitchIds' : freeswitchIds
        };
        $http.post('account/save', $scope.data).success(
                function (data, status) {
                    $scope.accounts.push(data);
                }).error(function () {
                });
        };

我的添加功能在控制器中,我可以重做它可以重做服务但是这个工作就是

答案 2 :(得分:0)

问题可能出在success的{​​{1}}。 addTask是异步的。因此执行顺序将是:1。TaskService.getTask中的http请求2. TaskService.taskList.push(data); 3. TaskService.getTasks成功回调。

$http

按此顺序,第2步毫无意义。因为第3步代码可能会覆盖.success(function(data, status, headers, config) { console.log(data); TaskService.getTasks(); TaskService.taskList.push(data);//pushing the new task //console.log("YYYYYYYYYYYYY -------->>>>>", defaultStart); })

TaskService.taskList

另一个错误的地方:

for (var i = 0; i < dataFromServer.length; i++) {
    TaskService.taskList[i] = dataFromServer[i];
};

此行代码出现两次。但是$scope.tasks = TaskService.getTasks(); 会返回TaskService.getTasks(),因为您没有放置关键字undefined

此外,您使用return的做法是错误的。 promise利用$http规范。因为您使用了promise,所以不要使用回调。您可能需要阅读promise个文档。