Navid_pdp11
Navid_pdp11

Reputation: 4032

how to inject $cookie in custom service of angularjs?

I am using angularjs and according to to its documentation i most use cookies with ngCookies. I add ngCookie with this structure :

  1. add angular.js and angular-cookies.min.js to my index.html
  2. inject ngCookie to to my app using this code :

    var app = angular.module('test',
    ['ngRoute','ngAnimate','ngFileUpload','ngSanitize','ngCookies']);
    
  3. and now i inject ng-cookie to my own service :

    app.service("transactionService",
    
      ["$cookie", "$http","sessionStorageService",
      function($cookie, $http, sessionStorageService){
    
            $cookies.put("unique_code",123456);
            console.log(sessionStorageService.getCurrentUser().sessionid);
            console.log($cookies.get("unique_code"));
            return;
        }
    ]);
    

but i am getting this error: Error: [$injector:unpr]

where am i wrong?

Upvotes: 3

Views: 1128

Answers (4)

Navid_pdp11
Navid_pdp11

Reputation: 4032

I found finally my fault and it was really simple and foolish.... my angular js version was 1.3.0 but i get cookie from angular version 1.4.4 :(

Upvotes: 0

Ruben Karapetyan
Ruben Karapetyan

Reputation: 469

if you use old Angular version then you should use $cookieStore instead of $cookie

app.service("transactionService",[
"$cookieStore","$http","sessionStorageService",

function($cookieStore, $http, sessionStorageService){

    $cookieStore.put("unique_code",123456);
    console.log(sessionStorageService.getCurrentUser().sessionid);
    console.log($cookieStore.get("unique_code"));
    return;
}]);

Upvotes: 2

Sudhansu Choudhary
Sudhansu Choudhary

Reputation: 3360

You have misspelled $cookies

     ["$cookie", "$http","sessionStorageService",
            ^
  function($cookie, $http, sessionStorageService){

Error: $injector:unpr => "Unknown Provider Error"

Check out injector:unpr error

Also $cookies documentation here

Upvotes: 2

miensol
miensol

Reputation: 41678

The name of the service is $cookies and not $cookie.

Side note when developing use full version (not minified) of angular it provides much better error codes. The Error: $injector:unpr is documented and well known:

This error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly.

Upvotes: 4

Related Questions