使用角度 ui 路由器获取服务中的路由参数

Fetching route parameters in service with angular-ui-router

本文关键字:服务 路由 参数 获取 路由器 ui      更新时间:2023-09-26

使用 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-ui-router以与默认 Angular 路由器相同的方式获取服务中的路由参数?

编辑:仍然有一些问题。使用加载程序内的 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
}

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