AngularJS:$routeParams在服务中工作

AngularJS: $routeParams to work within a service

本文关键字:服务 工作 routeParams AngularJS      更新时间:2023-09-26

我知道这很容易,但我无法完全理解如何做到这一点。

我需要在服务中执行API调用,以便在两个独立的控制器之间访问这些变量。

我遇到的问题是我无法访问服务中的$routeParams(获取时需要它)。我不知道如何将$routeParams从控制器传递到服务。

    app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    $scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    $scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
    var posts = function posts() {
        $http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
            console.log(JSON.stringify(res) );
        }); 
    };
            var description = '';
            var title = '';
            return {
                title: function () { return title; },
                setTitle: function (newTitle) { title = newTitle; },
                description: function () { return description; },
                setDescription: function (newDescription) { description = newDescription; },
                posts
        }; 
}]); 

工厂:

app.factory('Page', ['$http', function($http) {
        var _posts = function posts(param) {
          return  $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
        };
                var description = '';
                var title = '';
                return {
                    title: function () { return title; },
                    setTitle: function (newTitle) { title = newTitle; },
                    description: function () { return description; },
                    setDescription: function (newDescription) { description = newDescription; },
                    posts : _posts
            }; 
    }]); 

控制器:

app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    Page.posts($routeParams.slug).then(function success(response) {
       $scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);

请注意,success在Angular的较新版本中已弃用。我已经用then 更新了代码