0

I am moving all http calls in my controllers to services, using $q to promise... Everything seems to work till I refresh the page then the content disappears.

Setting: In my login service, I have a function which does an $http.post, it takes username and password. Then the response data is put in the promise.

Problem: Though the service works, It is trying resend the http call when the page is refreshed. The call then fails because the are no login details.

Question: How do I keep/store the original data so when the page is refreshed (and user is still signed in) and when I use the service in other controllers it does not do the http call it just returns the data?

Service:

var app = angular.module('myApp', ['ngRoute']);
app.factory('loginService', function($http, $q) {
    var deferResults = $q.defer();
     return {
    appContent: function(login_username, login_password) {
        $http.post('/login',{username: login_username, password: login_password}).success(function(data) {
          deferResults.resolve(myData);
      });
      return deferResults.promise;
    }
});

Controllers:

    function loginPageCtrl($scope, loginService) {
       $scope.login = function (login_username, login_password, login_rememberMe) {
          loginService.appContent(login_username, login_username).then(function (data) {
             $scope.pageOneContent = data;
          });
       };
    };

    function pageTwoCtrl($scope, loginService) {
      // Use the same data when page is refreshed
      // without having to pass-in login details

      loginService.appContent().then(function (data) {
         $scope.pageTwoContent = data;
      });
   };
4

1 回答 1

2

Of course that happens, your app loses all its state when the page is refreshed. You need to persist that username and password somewhere, like a cookie, and then retrieve that then make your second $http call, even better just keep a token in a cookie and use that for authentication. Use angular's $cookieStore to persist the login details:

var userData={username:login_username,password:login_password};
$cookieStore.put('user_data', userData);

and then when the controller loads, check if the cookie exists:

var userData = $cookieStore.get('user_data');
return userData

Check the source in this answer to see this in action.

To recap, every time the controller loads check the cookie, if its undefined then redirect the user to a login page, if it's not then extract the toke/username/password and make your $http call.

于 2014-03-17T10:04:49.970 回答