AngularJS - Script stops running at factory function with promise return

て烟熏妆下的殇ゞ 提交于 2019-12-24 12:09:19

问题


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.


回答1:


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 ) {


来源:https://stackoverflow.com/questions/51313285/angularjs-script-stops-running-at-factory-function-with-promise-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!