首页 > 解决方案 > Angular 的 HttpRequest 对象可以保存在本地存储中吗?

问题描述

在我的 Angular/Ionic 应用程序中,我想将 HttpRequest 对象保存到本地存储(使用 Ionic 的本机存储),在某些特定条件下从 http 拦截器调用:

public addRequestToQueue(request) {
    let queuedRequests = [];
    this.storage.get('queuedRequests').then((requests) => {
      if(requests) {
        queuedRequests = requests;
      }
      queuedRequests.push(request);
      this.storage.set('queuedRequests', queuedRequests);
    });
  }

但我在控制台中收到错误:

    Uncaught (in promise): DataCloneError: Failed to execute 'put' on 'IDBObjectStore': function () {
                _this.headers = new Map();
                Object.keys(headers).forEach(function ...<omitted>... } could not be cloned.
Error: Failed to execute 'put' on 'IDBObjectStore': function () {
                _this.headers = new Map();
                Object.keys(headers).forEach(function ...<omitted>... } could not be cloned.

如何将它们保存在本地存储中以备后用?可能吗?也许应该使用某种序列化方法?

标签: angulartypescriptionic-frameworkangular-http

解决方案


更新 在研究了一下这个错误后,我发现通常有一个框架或工具向 Array 原型添加属性,这使得它无法复制keys. 您可以参考以下关于 pouchdb 的github 讨论,其中用户遇到了类似的错误。

只是为了验证没有其他任何东西干扰您的存储,请尝试对请求进行编码并将其放入:

public addRequestToQueue(request) {
  this.storage.set('request', JSON.stringify(request));
});

这个


推荐阅读