AngularJS在自定义服务中使用角度模块

AngularJS use angular module in custom service

本文关键字:模块 自定义 服务 AngularJS      更新时间:2023-09-26

我有一个用于生成令牌的自定义服务,在此服务中我需要使用 MD5 函数,MD5 函数在模块中angular-md5

这是我的服务代码,generate_token函数使用来自 angular 模块的md5.createhash(),但我收到错误:TypeError: Cannot read property 'createHash' of undefined

我想我做错了什么,但我看不出是什么

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);
    }
}]);

您没有正确使用依赖数组注入

试试这个

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

只需在function($scope, md5)之前跳过括号,您应该没问题。在角度中,您有不同的注入语法可能性。参见:https://docs.angularjs.org/guide/di

你可能必须在函数之前在数组中定义 $scope 和 md5。

例如

    .controller('MainCtrl', ['$scope', 'md5', function($scope, md5) {
      $scope.$watch('email' ,function() {
        $scope.message = 'Your email Hash is: ' + md5.createHash($scope.email || '');
      });
    }]);