Angularjs视图未显示,由工厂引起

时间:2017-04-20 17:55:34

标签: angularjs

我在将工厂函数添加到AngularJs模块时遇到问题。

当我添加' authInterceptor '工厂功能到我的主页视图模块。视图无法加载。但是当我删除工厂功能时,它会加载。

我做错了什么?

家庭控制器

'use strict';

angular.module('myApp.home', ['ngRoute'])

.factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    responseError: function (rejection) {
      if (rejection.status === 401) {
        // handle the case where the user is not authenticated
      }
      return $q.reject(rejection);
    }
  };
})

.config(['$routeProvider', function($routeProvider, $httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
  $routeProvider.when('/', {
    templateUrl: 'home/home.html',
    controller: 'HomeCtrl'
  });

}])

.controller('HomeCtrl', function($scope, $http, $window) {
  console.log("Home Controller");


});

通用模块加载器

// public/js/app.js
angular.module('myApp', [
  'ngRoute',
  'myApp.home'

])
.config(['$locationProvider', '$routeProvider',
  function($locationProvider, $routeProvider, $httpProvider) {
    $locationProvider.hashPrefix('!');



    $routeProvider.otherwise({redirectTo: '/home'});
}])
.run(function($rootScope, $http){
  $rootScope.my_message = 'test';



});

1 个答案:

答案 0 :(得分:2)

问题是您的工厂有一个分号,它会破坏以下代码。

.factory('authInterceptor', function () {
  return 'a12345654321x';
}); //<==== remove this semicolon

//otherwise this breaks
.config(['$routeProvider', function($routeProvider, $httpProvider) {
  //etc

}])

编辑第二个问题:您缺少依赖项中的$ httpProvider。

.config(['$routeProvider', function($routeProvider, $httpProvider

=>

.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider