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

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

问题描述

我尝试在我的服务中的以下工厂中获取页面 post/:postId 上的 JSON 数据:

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 未定义.我究竟做错了什么?如果我对 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 参数?

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天全站免登陆