我有一个检索单个帖子的路由和一个查询我的 API 的服务.但是我需要将参数从 URL 传递给服务,以便我可以正确调用 API.我不知道该怎么做.
I have a route to retrieve a single post and a service to query my API to do so. But I need to pass parameters from the URL to the service so that I can call the API properly. I cannot wrap my head around how to do that.
这是我到目前为止所想出的.我省略了似乎与这个问题无关的内容.
This is what I have come up with so far. I left out what seemed not relevant for this question.
感谢您的帮助!
路由
myModule.config([
'$stateProvider',
'$urlRouterProvider',
'$locationProvider',
function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('post', {
url: '/posts/:hash_id/:slug',
templateUrl: '/js/app/views/post.html',
controller: 'PostCtrl',
resolve: {
postPromise: ['posts', function(posts, $stateParams){
//returns undefined
console.log($stateParams);
return posts.getOne($stateParams);
}]
}
})
// etc
服务
myModule.factory('posts', ['$http', 'auth', function($http, auth){
var o = {
posts: [],
post: {}
};
o.getOne = function(params) {
// Returns undefined
console.log(params);
return $http.get('/api/v1/posts/' + params.hash_id).success(function(data){
angular.copy(data, o.post);
});
};
return o;
}])
你错过了在 postPromise
resolve
You missed to add $stateParams
dependency in postPromise
resolve
代码
postPromise: ['posts', '$stateParams', function(posts, $stateParams){
这篇关于如何将 $stateParams 从 ui-router 传递给解析服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!