e.k
e.k

Reputation: 1363

Angular js cannot save cookies instead it throw undefined error

hi I try to save in cookies after a web response. Here is my code

angular.module('myApp').controller('SignInController',['WebService',function(WebService, $cookies){
    this.formData = {};
    this.signIn = function(formData){
        WebService.login(formData).then(function successCallback(data){
            //console.log("Success callback:"+JSON.stringify(data));
            var response = data.data;
            var message = response['message'];
            if (message == 'Success') {
                $cookies.put("id", response['id']); 
                $cookies.put("number", response['number']); 
            }else{

            }

            console.log('Message:'+message+" id:"+ $cookies.get('id'));
        },function errorCallback(error){
            console.log("Error"+JSON.stringify(error));
        });
        this.formData = {};
    };
}]);

i have included ngCookies as module while creating main angular module. What I'm doing wrong here? Anyone show me correct way. Thank you.

Upvotes: -1

Views: 125

Answers (1)

Praveen Soni
Praveen Soni

Reputation: 780

array containing all string of all arguments is good approach to handle dependency injection (DI) after your code is minified.

angularJs use Named_parameter in DI, you can understand how DI works by this blog post.

when you minified you angularJs file, ($http, $scope) converted to (a, b) and DI can't understand them.
$inject is my recommended way to handle this situation. its looks clean. (personal opinion, can be vary). and try to write code which easily maintainable.

var app = angular.module('myApp', []);
SignInController.$inject = ['WebService', '$cookies'];
app.controller('SignInCtrl', SignInController);

function SignInController(WebService, $cookies){
  this.formData = {};
  this.signIn = signIn;

  function signIn(formData) {
    WebService.login(formData)
      .then(successCallback, errorCallback);

    function errorCallback(error){
        console.log("Error"+JSON.stringify(error));
    }

    function successCallback(data){
       var response = data.data;
       var message = response['message'];
       if (message == 'Success') {
         $cookies.put("id", response['id']); 
         $cookies.put("number", response['number']); 
       }
    }
    this.formData = {};
};

Upvotes: 1

Related Questions