Search code examples
angularjsajaxcookiescookiestore

Setting a cookie in AJAX request with AngularJS


I am trying to set a cookie containing a token value retrieved from an Ajax request in AngularJS.

At first, I tested the result of the request by simply displaying the token value in my html page -> {{myToken}}. The result was correct. Now, I am trying to store that value in a cookie. The lines that I added for that purpose are written between **.

In my HTML page, I imported angular.min.js (v1.4.8), then angular-cookies.min.js (v1.6.3):

<!DOCTYPE html>
<html>

<head>

  <meta charset="UTF-8">
  <title>XXX</title>

  <link rel="stylesheet" href="assets/css/style.css" media="screen" type="text/css" />
  <script src="assets/scripts/angular.min.js"></script>
</head>

<body >

  <div ng-app="myApp" ng-controller="LoginCtrl">
    <h1>Log-in</h1><br>
    <form>
      <input type="text" name="user" placeholder="Username" ng-model="login">
      <input type="password" name="password" placeholder="Password" ng-model="password">
      <input type="submit" name="login" class="login login-submit" value="login" ng-click="myLogin()">
    </form>
    <div class="login-help">
      <a id="button-login" href="#">Register</a> • <a href="#">Forgot Password</a>
    </div>
<p>myToken: {{myToken}}</p>
  </div>

**<script src="assets/scripts/angular-cookies.min.js"></script>**
<script src="assets/scripts/myApp.js"></script>
<script src="assets/scripts/controllers/loginCtrl.js"></script>
</body>

</html>

myApp.js is quite simple for now:

var app = angular.module('myApp', [**'ngCookies'**]);

loginCtrl.js contains the Ajax request trigger when calling myLogin().

app.controller('LoginCtrl', function($scope, $http**, $cookieStore**) {
  $scope.login     = "";
  $scope.password  = "";
  $scope.myLogin = function() {
    $http({ <request>})
    .then(function(response) {
      $scope.myToken = <token value>;
      **$cookieStore.put('myToken', $scope.myToken);**
    })
  };
});

My page is stored on WampServer and when I reach it, I get the following error:

"Error: [$injector:unpr] http://errors.angularjs.org/1.4.8/$injector/unpr?p0=%24cookieStoreProvider%20%3C-%20%24cookieStore%20%3C-%20LoginCtrl


Solution

  • Ok, so I made a few noob mistakes. Here's what's now working for me:

    1. By using minified scripts, I needed to map the scopes "Uncaught Error: [$injector:unpr]" with angular after deployment
    2. I needed to declare the same versions of scripts. I am now using angular.min.js and angular-cookies.min.js version 1.6.3 (Index of /1.6.3/)
    3. As both repliers said, $cookieStores was deprecated a long time ago $cookieStore deprecated