$ state解析参数 - AngularJS $ StateProvider

时间:2015-04-19 17:37:43

标签: angularjs angular-ui-router

我尝试按照本指南here在我的路由中向resolve添加$state

通过向函数添加参数,比指南更进一步停止工作。

我的代码看起来像这样

'use strict';

angular.module('academiaUnitateApp')
  .config(function ($stateProvider, entryService) {
    var getEntry = function(id) {
        entryService.find(id)
            .then(function(response){
                return response.data;
            })
            .catch(function(error){
                return null;
            });
    };

    $stateProvider
        .state('entry', {
            url: '/entry/:id',
            templateUrl: 'app/entry/entry.html',
            controller: 'EntryCtrl',
            resolve: {
                entry: getEntry($state.current.param.id)
            }
        });
  });

但是我的控制台日志如下所示:

Uncaught Error: [$injector:modulerr] Failed to instantiate module academiaUnitateApp due to: //didn't add this part tell me if needed
Error: [$injector:unpr] Unknown provider: entryService

所以我可以更好地了解入门服务提供商是否已知,如果这是正确的,我应该如何添加它,而不是我现在添加它的方式。


<小时/>

修改

这是entryService

'use strict';

angular.module('academiaUnitateApp')
    .factory('entryService',function($http, $state){
        var service = {};

        service.find = function(_id){   
            return $http.get('/api/entrys/' + _id);
        };

        return service;
  });


应用程序/ app.js

'use strict';

angular.module('academiaUnitateApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'btford.socket-io',
    'ui.router',
    'ui.bootstrap',
    'textAngular'
])
  .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
    $httpProvider.interceptors.push('authInterceptor');
  })

  .factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
    return {
      // Add authorization token to headers
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if(response.status === 401) {
          $location.path('/login');
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  })

  .run(function ($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          $location.path('/login');
        }
      });
    });
  });

2 个答案:

答案 0 :(得分:2)

您需要提供应用程序模块所需的依赖项。为了能够注入您的服务,您的应用必须知道定义entryService的模块。

如果academiaUnitateApp.services是定义entryService的模块名称,则必须指定依赖关系,如下所示:

angular.module('academiaUnitateApp', ['academiaUnitateApp.services'])
  .config(function ($stateProvider, entryService) {
   // ...
});

然后您就可以在应用中注入所需的任何服务(或控制器......)。

答案 1 :(得分:1)

这是我的app.js(使用州的路由规则)

.state('books.show.detail',{
        url: '/detail/:bookId',
        templateUrl: 'views/book.detail.html',
        controller: 'BookDetailCtrl',
        resolve: {
          bookDetails: function(BookDetailsService,RestClient,$q,$stateParams){
            console.log($stateParams.bookId);
            var book = BookDetailsService(RestClient,$q,$stateParams.bookId);
            return book.get();
          }
        }
      });

这是我的service.js,其中BookDetailsService已定义

var services = angular.module('uiAngularClientApp.services',['ngResource']);

services.factory('RestClient',['$resource', function ($resource) {
  return $resource('http://localhost:8080/books/:id',{id:'@id'});
}]);

services.factory('BookDetailsService',['RestClient','$q',function(RestClient,$q,key){
  return function(RestClient,$q,key){
    return new GetBookDetails(RestClient,$q,key);
  };
}]);

function GetBookDetails($resource, $q, key) {
  this.get = function() {
    var delay = $q.defer();
    $resource.get({id:key},function(book){
      delay.resolve(book)
    },function(){
      delay.reject('Cannot get book details');
    });
    return delay.promise;
  };
};

完美无缺。最重要的是BookDetailsServiceservice.js的定义。