首页 > 解决方案 > 在 axios 承诺失败的情况下,如何有效地编写回退以从本地存储中获取对象?

问题描述

我正在尝试创建一个渐进式网络应用程序(我认为)。我已将标记中的按钮绑定到从 last.fm api 获取对象的方法

我想写一个回退,以防 API 没有响应从以前缓存的请求中获取相同的对象。

但是我注意到有两件事是错误的 1. cacheTopArtists 函数没有将我的对象正确保存到我的本地存储中。

    new Vue({
    el: '#LastFM',
    data() {
        return {
            myArtists: null
        }
    },
    mounted() {
        loadCachedTopArtists: {
            if (localStorage.cachedArtists) {
                this.myArtists = localStorage.cachedArtists;
            }
        }
    },
    methods: {
        getTopArtists: function(e) {
            axios
                .get("https://ws.audioscrobbler.com/2.0/?api_key=2c5c5c19e5d21ce9cf86b13712a1bbed&format=json&method=user.getTopArtists&user=El_Mayo&period=overall&limit=200")
                .then(response => (this.myArtists = response.data.topartists.artist))
                .catch(error => console.log(error))
            //if there is an error nothing should happen an this.myArtists is still equal to the localStorage.cachedArtists from line 31 (?);

        },
        cacheTopArtists: function(e) {
            localStorage.setItem('cachedArtists', JSON.stringify(this.myArtists));
        }
    },
    computed: {
        backgroundImage: function() {
            return (artist) => artist.image.find(size => size.size === 'large')['#text']
        }
    }
})

cachedArtists 键存在但为空。即使我设置了 myArtists : null 我认为条件仍然得到满足,因为我在里面写的代码正在显示

  1. 我认为这对我的 mount() 函数产生了连锁反应,该函数应该在页面加载时用 localstorage 版本填充我的空对象

我尝试将 getTopArtists 方法移动到 mount() 对象,以便它在页面加载时运行

我也尝试过 setItem 而不对 myArtists 对象进行字符串化。

这是带有 js 和 html 的笔 https://codepen.io/anon/pen/GaEaKp

没有错误消息,除了 cachedArtists 为空

标签: vue.jslocal-storageaxios

解决方案


cacheTopArtists第一 -如果从未调用过,为什么要保存一些东西?它应该在请求成功后调用。

第二 - 如果您希望页面加载时的“回退”行为,那么您应该将缓存加载例程放到axios .get(...) .catch(...)处理程序中。并getTopArtists在你的mounted钩子里打电话。

但最有效的方法是实现一个API模块,使用axios拦截器实现透明缓存,以防响应成功,拦截失败,返回缓存。

https://github.com/axios/axios#interceptors


推荐阅读