使用 angular-ui-router 在服务中获取路由参数

Fetching route parameters in service with angular-ui-router

使用 Angular 的默认路由器,您可以通过在路由中放置如下内容来解析 AJAX 资源:

.when('/view/:recipeId', {
    controller: 'ViewCtrl',
    resolve: {
      recipe: ["RecipeLoader", function(RecipeLoader) {
        return RecipeLoader();
      }]
    },

并实施此服务:

services.factory('RecipeLoader', ['Recipe', '$route', '$q',
    function(Recipe, $route, $q) {
  return function() {
    var delay = $q.defer();
    Recipe.get({id: $route.current.params.recipeId}, function(recipe) {
      delay.resolve(recipe);
    }, function() {
      delay.reject('Unable to fetch recipe '  + $route.current.params.recipeId);
    });
    return delay.promise;
  };
}]);

我目前正在开发 Ionic 应用程序,并提供以下服务:

services.factory('AlbumLoader', ['Album', '$route','$q', function (Album, $state, $q) { 
  return function () { 
    var delay = $q.defer();
    Album.get({id: $route.current.params.albumId}, function (album) { 
      delay.resolve(album);
    }, function() { 
      delay.reject('Unable to fetch album');
    });
    return delay.promise;
  } 
}]);

以及以下路线:

  .state('app.album', { 
    cache: false,
    url: "/albums/:albumId",
    resolve: { 
      album: ['AlbumLoader', function (AlbumLoader) { 
        return AlbumLoader();
      }]
    },
    views: { 
      'menuContent': { 
        templateUrl: "templates/album.html",
        controller: 'AlbumCtrl'
      } 
    } 
  })

Ionic 使用 angular-ui-router,它的文档在这个问题上不是很清楚。我怎样才能像默认 Angular 路由器一样使用 angular-ui-router 在服务中获取路由参数?

编辑:仍然有一些问题。在加载程序中使用 Chrome 调试器,当 URL 为 #/app/albums/17ef729c-af5b-4724-9c69-9585ab542e99 时,$state.params 是一个空对象。这会导致错误消息 Error: [$resource:badcfg] Error in resource configuration for action get. Expected response to contain an object but got an array,因为专辑 ID 未通过。

$state 的作用与 $route. 相同,只需将 $route 更改为 $state 并且其不嵌套在 $state.current.params 下使用 $state.params。或者你可以注入 $stateParams.

services.factory('AlbumLoader', ['Album', '$state', '$q', function(Album, $state, $q) {

  var delay = $q.defer();
  Album.get({
    id: $state.params.albumId
  }, function(album) {
    delay.resolve(album);
  }, function() {
    delay.reject('Unable to fetch album');
  });
  return delay.promise;
}]);

关于 $stateParams, jsbin 的文档:

这在你的状态配置中

.state("funnyState", {
            url: "/xxx/:id",
                templateUrl: "template.html",
                controller: "funnyController",
                resolve: {
                   thingINeed : function($stateParams, funnyService){
                        return funnyService.getReallyFunnyItem($stateParams.id);
                    }
                }
            })

在你的控制器中这个

angular.module("app.controllers").controller("funnyController", ["$state", "thingINeed", funnyController]);
    function funnyController($state, thingINeed){
//thingIneed is resolved promise
//$state contains the id -> $state.params.id
}

至少我在当前项目中是这样做的。