简体   繁体   English

使用拦截器在Ionic App中处理离线数据

[英]Handling offline data in a Ionic App using an interceptor

So a little bit of a background, I have this project and am working on Version 2 which involves adding in offline functionality. 因此,有一点背景知识,我有这个项目并且正在研究版本2,该版本涉及添加脱机功能。 I am stuck to the following stack as changing it now would involve to much overhead: 我坚持下面的堆栈,因为现在更改它会涉及很多开销:

Laravel API MYSQL Ionic Laravel API MYSQL离子

I have heard a lot about syncing using Pouch/CouchDB but unfortunately I can't change everything to use this stack. 我听说过很多有关使用Pouch / CouchDB进行同步的信息,但不幸的是,我无法更改所有内容以使用此堆栈。

I decided in my limited AngularJS/JS knowledge to use a HTTP Interceptor to intercept all requests, check if it is a POST/PUT request, check if the device is on/offline and either save the data in local storage or carry on with the request. 我决定在我有限的AngularJS / JS知识中使用HTTP拦截器来拦截所有请求,检查它是否是POST / PUT请求,检查设备是否在线/离线,然后将数据保存在本地存储中或继续使用请求。 This is where the issues begin. 这是问题开始的地方。

Here is my APIInterceptor: 这是我的APIInterceptor:

App.factory('APIInterceptor', function ($q) {

    return {
        request: function (config) {

            if(config.method == 'POST' || config.method == 'PUT')
            {
                //Add data to localstorage

                //Exit without actually sending the request to the server.
                return $q.reject();
            }

            return config || $q.when(config);
        }
    };
});

As you can see I am returning .reject() but what I need is mimic the API response and pass back to my service as if the request was processed successfully so my app can carry on as normal. 如您所见,我正在返回.reject()但我需要模仿API响应并将其传递回我的服务,就像请求已成功处理一样,以便我的应用可以正常进行。 Essentially returning success, status code 200 after the data was stored in localstorage. 数据存储在本地存储中后,本质上返回成功,状态码为200

Any suggestions on how I can do this? 关于如何执行此操作的任何建议?

Wouldn't that be easier to create a service where you manage all the http requests and, eventually, return your database data? 创建用于管理所有http请求并最终返回数据库数据的服务难道不是很容易吗?

Interceptors 拦截器

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. 出于全局错误处理,身份验证或请求的任何同步或异步预处理或响应的后处理目的,希望能够在将请求移交给服务器之前拦截请求,并在将请求移交给服务器之前将响应拦截发起这些请求的应用程序代码。 The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing. 拦截器利用promise API满足同步和异步预处理的这一需求。

I guess you don't need to check if the device is online/offline as you would get a requestError in your interceptor. 我猜您不需要检查设备是否在线/离线,因为您会在拦截器中收到requestError

Since you want to intercept the communication before it actually happens you can use this sort of interceptor: 由于您想在实际发生通信之前就对其进行拦截,因此可以使用这种拦截器:

.factory('APIInterceptor', function APIInterceptor($q) {
    return {
            request: function (config) {
                if(config.method == 'POST' || config.method == 'PUT')
                {
                    return $q.reject({status: 503, config: config});
                }
                return config || $q.when(config);
            },

            // response: function (httpResponse)
            // {
            //     return httpResponse || $q.when(httpResponse);
            // },

            responseError: function (rejection)
            {
                if (rejection.status === 503) {
                    rejection.status = 200;
                    rejection.statusText = "OK";
                    rejection.data = {};
                    return $q.resolve(rejection);
                }
                return $q.reject(rejection);
            }
        };
});

If the request is POST or PUT you can reject it adding a status and passing the configuration as well: 如果请求是POSTPUT ,则可以添加状态并通过配置来拒绝它:

if(config.method == 'POST' || config.method == 'PUT')
{
    return $q.reject({status: 503, config: config});
}

responseError will be processed. responseError将被处理。
Now you can check your status and resolve the promise so that your $http call does not catch an exception: 现在,您可以检查状态并解决承诺,以便您的$http调用不会捕获异常:

if (rejection.status === 503) {
    rejection.status = 200;
    rejection.statusText = "OK";
    rejection.data = {};
    return $q.resolve(rejection);
}

I've appended a data object cause that's what your http call might expect. 我附加了一个data对象,原因就是您的http调用可能期望的原因。 Basically, what we're doing here is trying to recreate a proper response. 基本上,我们在这里正在尝试重新创建适当的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用带电容器的 Ionic 应用程序为 firebase 实时数据库启用离线 - Enabling offline for firebase realtime database using Ionic app with capacitor 离线应用程序中的数据同步 - Data synchronization in offline App HTTP拦截器使用离子/角度导致CORS问题 - HTTP interceptor causing CORS issue using ionic/angular 如何使用angular js在Ionic App中添加数据和数据流 - How to add data and data flow in Ionic App using angular js 在Ionic应用中返回数据 - Return data in ionic app 离线时处理 Progressive Web App 中的获取请求 - Handling fetch requests in Progressive Web App when offline 使用http拦截器 - Angular 5 - Ionic 3从离子存储设置默认请求标头 - Setting default requests header from ionic storage using http interceptor - Angular 5 - Ionic 3 如何使用离子科尔多瓦应用程序对设备上的本地表单数据进行加密 - how to encrypt the local form data on the device using ionic cordova app 使用Cloud Firestore的Ionic App-查看所有用户的数据 - Ionic App using Cloud Firestore - See data for all users 将来自 firebase 的数据存储到 firebase 离线存储与 ionic 5 - store data from firebase into firebase offline storage with ionic 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM