0

I create a factory where I put my http request for adding, retrieving and deleting tasks.

Now when I add a task you don't see the visual change. I have to refresh the browser. Now to fix this I figured I would write a function to check the length of the old array against the length of the new one and set an interval off 1 minutes on it to make this change and then pull in the tasks. I am able to log my length change of the array but nothing happens visually (still have to refresh the browser).

If anybody could help me out here.

Part of my app.js code:

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)
GY22
  • 755
  • 2
  • 17
  • 48
  • So when u call service u call get method and u put your tasks in array of objects ok? On add u send post request on server. so when u refresh u call again get method and u fetch that newly created object. If u want to see it without refresh just push that newly created object in array of objects. $scope.tasks.push(newTask). You can do that in button submit function – dev_in_progress Aug 14 '15 at 14:08

3 Answers3

0

This might be what you're looking for, by using $interval you can set an interval every x seconds:

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

And then inject $interval into your factory:

zazzleApp.factory('TaskService', function ($http, $interval).....
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
0

Try this:

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

reference: https://stackoverflow.com/a/24836089/3330947

Update:

I did it like this:

Service (fetch all accounts):

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

Controller:

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

My add function is in controller, i thin it can be redone to be service but this work soo

Community
  • 1
  • 1
dev_in_progress
  • 2,484
  • 2
  • 21
  • 32
  • @dev_in_progess. if i apply $scope.$apply(function() { $scope.pins.push(data); }); in my succes . i get an error -> https://gyazo.com/e86ed78625dc5e4467f5df29b99a2709 – GY22 Aug 14 '15 at 14:25
  • whel u dont have $scope defined, add $scope in your factory – dev_in_progress Aug 14 '15 at 14:26
  • -> mmm this does not seem to help (https://gyazo.com/c4c40dbb258dab5ac5798e8fbf68d67c) – GY22 Aug 14 '15 at 14:43
0

The problem may be in success of addTask. TaskService.getTaskis async. So the execute order will be: 1. http request in TaskService.getTasks 2. TaskService.taskList.push(data); 3. $http success callback.

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

In this order, step 2 is pointless. Because step 3 code may override TaskService.taskList

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

And another wrong place:

$scope.tasks = TaskService.getTasks();

this line code appears twice. But TaskService.getTasks() returns undefined because you don't put keyword return.

In addition, your practice to use promise is wrong. $http leverages promise specification. Don't use callback since you used promise. You may need read promise docs.

gzc
  • 8,180
  • 8
  • 42
  • 62