javascript - 从状态设置工厂变量

标签 javascript angularjs wordpress ionic-framework

我正在使用工厂通过 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/

相关文章:

javascript - 在 javascript 中从 Wordpress REST API 正确设置数组

javascript - 我如何从图表中获取带有 ID 的 SVG?

javascript - 如何在文本结束后放置冒号

javascript - typescript ,类未定义

javascript - 为什么路由在这段代码中不起作用?

wordpress - 如何从二十二号中删除margin-top : 32px ! important

php - Custruct正确的查询: WP_Term_Query with child_of,深度和meta_query

javascript - Promise 和异步函数 "borrowing"来自同时运行的 Promise 的变量

angularjs - 仅在 AngularJS 加载时第一次运行函数

javascript - 使用 "Controller As"语法时,有没有办法获取 Angular Controller 的命名空间?