[英]Set factory variable from state
我正在使用工廠使用Rest-API獲取Wordpress中不同類別的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]設置為變量,可能是狀態名,也可以是我可以只調用一次wordpress的東西,而url將取決於用戶選擇的狀態是什么? 我一直在嘗試學習角度知識,從我所看到的東西中我可以肯定,必須有一種更優雅的方式來做這樣的事情?
注入Angular $ location提供程序,您將可以訪問當前URL的每個部分(也可以使用它來偵聽狀態更改)。 然后,只需動態構建URL到Wordpress:
.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) { // ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.