AngularJS:$routeParams在服务中工作
AngularJS: $routeParams to work within a service
我知道这很容易,但我无法完全理解如何做到这一点。
我需要在服务中执行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
更新了代码
相关文章:
- angular2中的全局服务不工作
- fetch事件处理程序中的fetch()未触发服务工作程序中的fetch事件
- JQuery-HTML到PDF没有'无法在IE中工作(来自C#asmx Web服务)
- 序列化方向结果到 JSON 发送到我的网络服务无法正常工作
- 服务工作线程是否可以响应同步 XHR 请求
- 增加服务工作线程的生命周期
- 角度工厂和服务工作,但不如预期
- 忽略服务工作进程请求中的查询参数
- 了解服务工作进程范围
- 角度服务无法正常工作
- 使用服务跟踪用户状态并使 $watch() 正常工作
- iOS 移动 Safari 服务工作进程缓存限制
- 服务工作线程是否可以缓存 POST 请求
- 注册服务工作进程返回中止错误代码:20
- AngularJS模态服务停止工作
- 如何删除有缺陷的服务工作线程,或实现“终止开关”
- 尽管其他控制器和服务工作,未知的提供者错误
- 服务工作进程基本设置
- 使用服务工作进程的提取事件中的字符串创建 HTML 响应
- 美元.ajax POST到我的web服务工作正常,但GET请求失败错误405方法不允许