AngularJS - Script stops running at factory function with promise return
Asked Answered
Q

1

1

I've been learning/working on a newbie project which is basicly a simple task manager(similiar to those todo list projects). And I designed a user login page for this project and here is how it works.

So I have two functions siteLogin() for logging in and inside it I want to use second function showTasks() after user logs in which returns the usertasks it gets from API (promises I know).

So first I needed to return a value from a $http inside the showTasks() function but I ended up returning something like $$state so I searched and found couple of solutions on this website and so far I learned that $http doesn't return value but returns promises. So after couple of try&fail my code now runs until showTasks() and stops there.

So here is my code now.

Factory

app.factory('userTaskList', function ($http) {

    return {
        showTasks: function (userName) {
            var tasks = { K_ADI: userName }; //UserName of the per 
            var $promise = $http({
                method: 'POST',
                url: 'http://localhost:5169/api/Isler/' + userName + '/IstenilenKayitCek',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: tasks
            });
            $promise.then(function successCallback(response) {
                var data = response.data;
                console.log("Factory data:", response);
                return success(data);

            }, function errorCallback(response) {     
                error("Error");
            });
        }
    }
});

And my Controller:

 app.controller('myCtrl', ['$scope', '$http', function ($scope, $http,userTaskList ) {

 $scope.siteLogin = function () {
    var loginMember = {
        K_ADI: $scope.panel.loginUserName,  
        PAROLA: $scope.panel.loginPassword  // HTML input 
    };
    console.log(loginMember);
    $http({
        method: 'POST',
        url: 'http://localhost:5169/api/Kullanicilar/KullaniciDogrula',
        headers: {
            'Content-Type': 'application/json'
        },
        data: loginMember
    }).then(function successCallback(response) {
        console.log("Message sent", response);
        $scope.data = response.data.error.data;
        if ($scope.data === true) {

            console.log("User exists in database");

            //RUNS UNTIL HERE AND STOPS

            userTaskList.showTasks($scope.panel.loginUserName)
                .then(function (res) {
                    $scope.gorev = res;
                    console.log("Fonk ici : ", $scope.gorev);
                    console.log("222222", res);
                }, function (err) {
                    console.log(err);
                });
            console.log("outside func : ", $scope.gorev);     
        } 
    }, function errorCallback(response) {
        console.log("Error: ", response);
    });
}
}]);

This may be seen like a duplicate and there are many similiar problems on stack but I tried those solutions (I will link some later) still didn't solve my this problem plus some of them created other problems like this one. I tried to use $q , nested .then, and finally defining code in factory then calling its instance in module and so on. But still not working.

NOTE:Sorry for my poor English.

Quincey answered 12/7, 2018 at 19:39 Comment(2)
What do you mean stops? Any errors in the console? What does the response look like? You have response.data.error.data, could this be producing a null pointer exception?Abrasive
@SumamaWaheed no errors about it at all. The last thing I see in consol is "User exists in database and I dont see the rest of the consol logs. about the response.data.error.data its because its agroup Project and my friend coded API in a lame way. So I needed to reach the data like that. I used it in other functions that I didnt posted here so I know its not that.Quincey
P
2

There are several errors in the showTasks function:

app.factory('userTaskList', function ($http) {

    return {
        showTasks: function (userName) {
            var tasks = { K_ADI: userName }; //UserName of the per 
            var $promise = $http({
                method: 'POST',
                url: 'http://localhost:5169/api/Isler/' + userName + '/IstenilenKayitCek',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: tasks
            });
            var derivedPromise = $promise.then(function successCallback(response) {
                var data = response.data;
                console.log("Factory data:", response);
                ̶r̶e̶t̶u̶r̶n̶ ̶s̶u̶c̶c̶e̶s̶s̶(̶d̶a̶t̶a̶)̶;̶
                //IMPORTANT
                return data;

            }, function errorCallback(response) {     
                ̶e̶r̶r̶o̶r̶(̶"̶E̶r̶r̶o̶r̶"̶)̶;̶
                console.log(response.status);
                //IMPORTANT
                throw response;
            });
            //IMPORTANT
            return derivedPromise;
        }
    }
});

The desired data needs to be returned to the .then method success handler.

Errors in the error handler need to be re-thrown. Otherwise the rejected promise will be converted to a success with a value of undefined.

Finally the derived promise needs to be returned to the showTasks function.


Update

Do you think I call the function correctly inside the $scope.siteLogin ?

The dependency injection is wrong:

̶a̶p̶p̶.̶c̶o̶n̶t̶r̶o̶l̶l̶e̶r̶(̶'̶m̶y̶C̶t̶r̶l̶'̶,̶ ̶[̶'̶$̶s̶c̶o̶p̶e̶'̶,̶ ̶'̶$̶h̶t̶t̶p̶'̶,̶ ̶
    function ($scope, $http,userTaskList ) {

Should BE

app.controller('myCtrl', ['$scope', '$http', 'userTaskList', 
    function ($scope, $http,userTaskList ) {

OR

app.controller('myCtrl', function ($scope, $http,userTaskList ) {
Phosphate answered 12/7, 2018 at 20:11 Comment(3)
Thanks that solved my problem! I choose your reply as answer and this is a little off topic but as I mention in my question I still can't Access the data outside the function though console.log("outside func : ", $scope.gorev); still prints undefined to console. Can you give me any tips on that?Quincey
That's the way asynchronous operations work. Operations are non-blocking which means the JavaScript engine immediately executes the next lines. The code inside the .then block is held until results arrive from the server.Phosphate
Non-blocking operations are one of the most powerful features of functional programming and one commonly mis-understood by new JavaScript programmers.Phosphate

© 2022 - 2024 — McMap. All rights reserved.