我正在使用工厂获取wordpress中使用Rest-API的不同类别的feed数据,我想知道我是否把它弄得一团糟。
我有大约13个不同的类别,我只做了一个基本的调用,看起来像这样:
.factory('Articles1', function ($http) {
var articles1 = [];
storageKey = "articles1";
function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}
return {
all: function () {
return $http.get("http://www.example.com/wp-json/posts?filter[category_name]=category1").then(function (response) {
articles1 = response.data;
console.log(response.data);
return articles1;
});
},
get: function (articleId) {
if (!articles1.length)
_getCache();
for (var i = 0; i < articles1.length; i++) {
if (parseInt(articles1[i].ID) === parseInt(article1Id)) {
return articles1[i];
}
}
return null;
}
}
})
对于13个类别中的每个类别都有一个单独的调用来获取文章。
是否有一种方法来设置[category_name]到一个变量,可能是状态名称或一些东西,我可以只是让1调用wordpress和url将依赖于什么状态用户选择?我一直在努力学习angular,从我所看到的,我确信一定有一种更优雅的方法来做这样的事情。
注入Angular的$location提供商,你就可以访问当前URL的每个部分(你也可以用它来监听状态的变化)。然后动态地构建Wordpress的URL:
.factory('Articles1', function ($http, $location) {
// ...
return {
all: function () {
var currentCategory = $location.path().split('/')[1]; // Assuming the category is part of the path and at the second place
var wpUrl = 'http://www.example.com/wp-json/posts?filter[category_name]=' + currentCategory;
return $http.get(wpUrl).then(function (response) { // ...