javascriptangularjsangularjs-serviceangularjs-module

AngularJS use angular module in custom service


I have a custom service for generating token, in this service I need to use an MD5 function, the MD5 function is in the module angular-md5

here is my service code, the generate_token function use md5.createhash() from the angular module but I'm getting ths error : TypeError: Cannot read property 'createHash' of undefined

I think I have made something wrong but I can't see what

angular.module('app.services', ['angular-md5'])

.service('Auth', [function($scope, md5){
    var self = this;

    this.rand_alphanumeric = function() {
        var subsets = [];
        subsets[0] = [48, 57]; // ascii digits
        subsets[1] = [65, 90]; // ascii uppercase English letters
        subsets[2] = [97, 122]; // ascii lowercase English letters 

        // random choice between lowercase, uppercase, and digits
        s = Math.floor(Math.random() * 2) + 0
        ascii_code = Math.floor(Math.random() * (subsets[s][1] - subsets[s][0] + 1) + subsets[s][0]);
        return String.fromCharCode(ascii_code);
    }

    this.generateToken = function() {
        var str = "";
        for (var i = 0; i < 8; i++) 
            str += self.rand_alphanumeric();
        return md5.createHash(str);
    }
}]);

Solution

  • You are not using the dependency array injection properly

    Try this

    angular.module('app.services', ['angular-md5'])
    
    .service('Auth', ['$scope','md5',function($scope, md5){
    var self = this;