我正在使用工厂通过 Rest-API 获取 WordPress 中不同类别的提要数据,我想知道我是否把它弄得一团糟。
我有大约 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] 设置为变量,可能是州名称或其他名称,我只需对 wordpress 进行 1 次调用,并且 url 将取决于用户选择的州?我一直在尝试学习 Angular ,从我所看到的情况来看,我确信一定有一种更优雅的方式来做这样的事情?
最佳答案
注入(inject) 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) { // ...
关于javascript - 从状态设置工厂变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273171/