最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Redirecting to another page prevents functions from returning their values - Stack Overflow

programmeradmin3浏览0评论

I have a Login page and if user logs in I want to redirect the user to another HTML page where I will list users tasks that I get from server.

The problem is:

Even though the functions I wrote works properly and backend API returns the values I want (I can see the value details on Console) when I use redirect code $window.location.href = '../Kullanici/userPanel.html the page redirects immedietly after login and for some reason I can't use the values returned by functions after redirection. Not only that I can't see the details of the value returned on console log anymore.

And here is my code for it:

Controller:

app.controller('myCtrl', ['$scope', '$http', '$window','$mdToast', 'userTaskList',
    function ($scope, $http, $window, $mdToast, userTaskList) {
        $scope.siteLogin = function () {

            var userName = $scope.panel.loginUserName;
            var password = $scope.panel.loginPassword;
            var loginMember = { //JSON data from login form
                K_ADI: $scope.panel.loginUserName,
                PAROLA: $scope.panel.loginPassword
            };
            $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) {//if username and password is correct

                    console.log("User exists");
                    userTaskList.showActiveTasks(userName)
                        .then(function (activeTaskResponse) {
                            var activeTasks = activeTaskResponse;
                            console.log("Active tasks (controller): ", activeTaskResponse);

                            userTaskList.showFinishedTasks(userName)
                                .then(function (finishedTaskResponse) {
                                    var finishedTasks = finishedTaskResponse;
                                    console.log("Finished tasks(controller): ", finishedTaskResponse);
                                    $scope.getMessage();
                                    $window.location.href = '../Kullanici/userPanel.html';
                                }, function (err) {
                                    console.log(err);
                                });

                        }, function (err) {
                            console.log(err);
                        });

                }

            }, function errorCallback(response) {
                console.log("Couldn't send", response);
            });
        }

So what causes this problem and how can I fix it?

Edit: I nested .then parts but it doesnt work properly and gives This value was just evaluated now warning. So I stil can't use data on the redirected HTML page.

I also removed the factory since it makes the code look really messy and its probably not the source of the problem.

I have a Login page and if user logs in I want to redirect the user to another HTML page where I will list users tasks that I get from server.

The problem is:

Even though the functions I wrote works properly and backend API returns the values I want (I can see the value details on Console) when I use redirect code $window.location.href = '../Kullanici/userPanel.html the page redirects immedietly after login and for some reason I can't use the values returned by functions after redirection. Not only that I can't see the details of the value returned on console log anymore.

And here is my code for it:

Controller:

app.controller('myCtrl', ['$scope', '$http', '$window','$mdToast', 'userTaskList',
    function ($scope, $http, $window, $mdToast, userTaskList) {
        $scope.siteLogin = function () {

            var userName = $scope.panel.loginUserName;
            var password = $scope.panel.loginPassword;
            var loginMember = { //JSON data from login form
                K_ADI: $scope.panel.loginUserName,
                PAROLA: $scope.panel.loginPassword
            };
            $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) {//if username and password is correct

                    console.log("User exists");
                    userTaskList.showActiveTasks(userName)
                        .then(function (activeTaskResponse) {
                            var activeTasks = activeTaskResponse;
                            console.log("Active tasks (controller): ", activeTaskResponse);

                            userTaskList.showFinishedTasks(userName)
                                .then(function (finishedTaskResponse) {
                                    var finishedTasks = finishedTaskResponse;
                                    console.log("Finished tasks(controller): ", finishedTaskResponse);
                                    $scope.getMessage();
                                    $window.location.href = '../Kullanici/userPanel.html';
                                }, function (err) {
                                    console.log(err);
                                });

                        }, function (err) {
                            console.log(err);
                        });

                }

            }, function errorCallback(response) {
                console.log("Couldn't send", response);
            });
        }

So what causes this problem and how can I fix it?

Edit: I nested .then parts but it doesnt work properly and gives This value was just evaluated now warning. So I stil can't use data on the redirected HTML page.

I also removed the factory since it makes the code look really messy and its probably not the source of the problem.

Share Improve this question edited Jul 28, 2018 at 16:21 georgeawg 49k13 gold badges77 silver badges98 bronze badges asked Jul 18, 2018 at 8:01 user8008566user8008566 13
  • This code needs deep edits! First thing first your login functionality should go to a service and in your controller you should only ask the service to do the dirty data job. Second, by using $window.location.href you are killing your app! if after successful login you want to be staying in your app, you'd need to use $location service. – Babak Commented Jul 18, 2018 at 14:48
  • @Babak sorry I'm a beginner in Angular. Can you please show it to me with code ? Atleast the $location service part because I didnt understand why its killing the app . – user8008566 Commented Jul 18, 2018 at 18:39
  • The question has been edited so many times that it is unclear what you are asking. Did you originally have the assignment of $window.location.href at the end of the siteLogin function? And now you have moved it to the bottom of the three nested .then methods? If that is the case, are you now getting the data from the server and then losing it when $window.location.href gets assigned? – georgeawg Commented Jul 22, 2018 at 21:06
  • @georgeawg I edited the code after Jacques Olivier's answer. Before that .thens wasn't nested and I couldn't even see the data on Console. So originally wherever I put $window.location.href it didn't solve my problem. Now after I edited code like Jacques Olivier's answer I can see that response returned from API in the console but I can't use nor see the data inside it. So I got close to solution but still having the main problem which is not being able to use the data on the HTML page that code redirects me. – user8008566 Commented Jul 23, 2018 at 7:18
  • @georgeawg I'll probably edit my question one last time to give mor clear details after trying your answer. – user8008566 Commented Jul 23, 2018 at 7:19
 |  Show 8 more ments

2 Answers 2

Reset to default 6

I would have nested the your two functions inside the first promise, then redirect once all of them are done. Something like

app.controller('myCtrl', ['$scope', '$http', '$window','$mdToast', 'userTaskList',
  function ($scope, $http, $window, $mdToast, userTaskList) {
    $scope.siteLogin = function () {

        var userName = $scope.panel.loginUserName;
        var password = $scope.panel.loginPassword;
        var loginMember = { //JSON data from login form
            K_ADI: $scope.panel.loginUserName,
            PAROLA: $scope.panel.loginPassword
        };

        $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) {//if username and password is correct

                console.log("User exists");
                userTaskList.showActiveTasks(userName)
                    .then(function (res) {
                        var activeTasks = res;
                        console.log("Active tasks (controller): ", res);

                        userTaskList.showFinishedTasks(userName)
                        .then(function (res) {
                            var finishedTasks = res;
                            console.log("Finished tasks(controller): ", res);
                            $scope.getMessage(); 
                            $window.location.href = '../Kullanici/userPanel.html';
                        }, function (err) {
                            console.log(err);
                        });

                    }, function (err) {
                        console.log(err);
                    });

            } else { //if username or password is wrong
                $mdToast.show(
                    $mdToast.simple()
                        .textContent('Username or Password is wrong')
                        .position('right')
                        .hideDelay(3000)
                            );      
            } 
        }, function errorCallback(response) {
            console.log("Couldn't send", response);
        });          
     }
   }
]);

Oh I injected ngRoute to my AngularJS module but haven't use it yet.

Using $window.location.href kills the app and loads the other page, losing $rootScope, $scope, and all service data.

Re-factor your code to use a router and store the data in a service:

$routeProvider
 .when('/userPanel' , {
     templateUrl: 'partials/userPanel.html',
     controller: panelController
})
 panelService.set(data);
 $location.path("/userPanel.html");     

OR use localStorage to store the data:

 localStorage.setItem('panelData', JSON.stringify(data));
 $window.location.href = '../Kullanici/userPanel.html';

Data stored in a service will survive route changes (which destroy $scope). Data stored in localStorage will survive page changes (which destroy apps).


The code can be simplified

This will solve the problem of having the page wait for the data before changing the route.

Since the getMessages function makes an HTTP request it needs to be modified to return a promise:

$scope.getMessages = getMessages;
function getMessages() {
    return $http({
        method: 'GET',
        url: 'http://localhost:5169/api/chat/chatCek'
    }).then(function successCallback(res) {
        console.log("Mesajlar", res);
        $scope.messages = res.data.error.data;
        return res.data.error.data;
    }, function errorCallback(res) {
        console.log("Hata", res);
        throw res;
    });
}

Then to delay the changing of the route until the getMessages data returns from the server, chain from the getMessages promise:

$http({
    method: 'POST',
    url: 'http://localhost:5169/api/Kullanicilar/KullaniciDogrula',
    data: loginMember
}).
  then(function successCallback(response) {
    console.log("message sent", response);
    $scope.data = response.data.error.data;
    if ($scope.data !== true) { throw "user error" };
    //username and password is correct
    console.log("User exists");
    return userTaskList.showActiveTasks(userName);
}).
  then(function (activeTaskResponse) {
    var activeTasks = activeTaskResponse;
    console.log("Active tasks (controller): ", activeTaskResponse);
    return userTaskList.showFinishedTasks(userName)
}).
  then(function (finishedTaskResponse) {
    var finishedTasks = finishedTaskResponse;
    console.log("Finished tasks(controller): ", finishedTaskResponse);
    //CHAIN from getMessages promise
    return $scope.getMessages();
}).
  then(function(data) {
    console.log(data);
    //SAVE data before changing route
    panelService.set(data);
    $location.path( "/userPanel" );
    //OR STORE data before changing app
    //localStorage.setItem('panelData', JSON.stringify(data));             
    //$window.location.href = '../Kullanici/userPanel.html';
}).
  catch(function (response) {
    console.log("Couldn't send", response);
    throw response;
});
发布评论

评论列表(0)

  1. 暂无评论