angularJS $stateParams in service

让人想犯罪 __ 提交于 2019-12-11 19:13:04

问题


I try to fetch JSON data on the page post/:postId within the following factory in my service:

angular.module('sampleapp.services', [])
    .factory('DetailService', function($http) {
        return {
            getDetail: function(callback) {
                $http.get('https://example.com/posts/' + $stateParams.postId + '.json').success(callback);
            }
        };
    });

Unfortunately, $stateParams is undefined. What am I doing wrong? If I hardcode the URL, it works.

My routing:

.state('detail', {
    url: '/post/:postId',
    templateUrl: 'templates/detail.html',
    controller: 'DetailCtrl'
})

and my controller:

.controller('DetailCtrl', function ($scope, DetailService) {
    DetailService.getDetail(function(data) {
        $scope.post = data;
    });
});

My question is: How can i access the URL-paramters within my factory?


回答1:


Just like you inject the $http service, you must also inject the $stateParams service:

.factory('DetailService', function($http, $stateParams) {


来源:https://stackoverflow.com/questions/21799161/angularjs-stateparams-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!