试图得到区间函数与我的工厂工作



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

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

如果有人能帮我一下。我的app.js代码的一部分:

global vars -> 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)

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

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

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

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

试试这个:

$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 () {
                });
        };

我的add函数是在控制器中,我认为它可以被重新制作为服务,但这个工作

问题可能在addTasksuccessTaskService.getTask是异步的。所以执行顺序是:1。TaskService.getTasks的http请求TaskService.taskList.push(数据);3.$http成功回调。

.success(function(data, status, headers, config) {
        console.log(data);
        TaskService.getTasks();
        TaskService.taskList.push(data);//pushing the new task
        //console.log("YYYYYYYYYYYYY -------->>>>>", defaultStart);
})

按照这个顺序,步骤2是没有意义的。因为第三步代码可能会覆盖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。你可能需要阅读promise文档

最新更新