添加工厂获取错误:[$ injector:unpr]

时间:2017-10-05 10:42:26

标签: javascript angularjs

尝试添加一个简单的工厂并收到错误:

Error: [$injector:unpr] http://errors.angularjs.org/1.4.6/$injector/unpr?p0=subfactoryProvider%20%3C-%20subfactory%20%3C-%20authService%20%3C-%20AuthorizationInterceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile

我添加了一个脚本标记:

<script src="app/subfactory.js"></script>

子要求定义如下:

(function () {
    //'use strict';

    angular
        .module('app')
        .factory('subfactory', subfactory);

    function subfactory() {

        var subValue = {};
        return {
            set: set,
            get: get
        };

        function get() {
            return subValue;
        }

        function set(value) {
            subValue = value;
        }
    }

});

在authService中使用:

(function () {
    //'use strict';

    angular
        .module('app')
        .factory('authService', authService);

    authService.$inject = ['subfactory'];

    function authService(subfactory) {

       // removed code for brevity

        mgr.getUser().then(function (user) {
            if (user) {
                var idToken = user.id_token;
                var dataIdToken = getDataFromToken(idToken);
                subfactory.set(dataIdToken.sub);
            } else {
                //console.log("User not logged in");
            }
        });

我也有调用authService的AuthorizationInterceptor:

app.factory("AuthorizationInterceptor", ['$q', '$injector', '$rootScope', '$window', 'authService', function ($q, $injector, $rootScope, $window, authService) {

请问,我该如何解决此错误?

编辑:

<script src="app/app.js"></script>
<script src="app/authService.js"></script>
<script src="app/subfactory.js"></script>

app.factory("AuthorizationInterceptor"...app.js

中定义

错误消息是F12控制台中唯一的消息。

2 个答案:

答案 0 :(得分:2)

尝试翻转声明文件的顺序,如下所示:

// only define your module here
<script src="app/app.js"></script>

// define your factories
<script src="app/subfactory.js"></script>
<script src="app/authService.js"></script>

// define your authorization factory here just like the previous two
<script src="app/Authorization.js"></script>

答案 1 :(得分:1)

无法将其添加为评论。所以在这里添加答案。您需要更改文件声明的顺序。在您的情况下,错误是因为您在authService.js之前有subfactory.jsauthService.js搜索其依赖关系,但未找到它subfactory.js但尚未添加。

 <script src="app/app.js"></script>// If it main file whre angular module is created
<script src="app/subfactory.js"></script>
<script src="app/authService.js"></script>