angularJS $ stateParams服务 [英] angularJS $stateParams in service

查看:1469
本文介绍了angularJS $ stateParams服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在页面后获取JSON数据/:帖子ID下面的工厂内在我的服务

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);
            }
        };
    });

不幸的是,$ stateParams是不确定的。我究竟做错了什么?如果我硬code中的URL,它的工作原理。

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

我的路由

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

和我的控制器

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

我的问题是:如何访问我的工厂内的URL-paramters

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

推荐答案

只是喜欢你注入$ http服务,还必须注入$ stateParams服务:

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

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

这篇关于angularJS $ stateParams服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆