角度httpclient自定义json解析器

角度httpclient自定义json解析器

本文介绍了角度httpclient自定义json解析器(jsog)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是发现了新的Angular 4.3.x HttpClient 模块,所以我很可能会忽略一些简单的事情.

I'm just discovering the new Angular 4.3.x HttpClient Module, and I may very well be overlooking something simple.

我想知道是否可以注册自定义JSON反序列化器,并且仍然可以从键入的 HttpClient get/post/put中受益.由于性能原因,我的后端返回了JSOG(这是JSON的扩展),而不是 JSON 内容.

I would like to know if it is possible to register a custom JSON Deserializer and still get the benefit of the typed HttpClient get/post/put. It happens that for performance reason, my backend returns JSOG, which is an extension of JSON, instead of JSON content.

当前,我使用普通的 get(url,{responseType:'text'})发出所有请求,然后通过RxJs Map Operation运行响应以转换 Observable< string>; 在我想要的Observable中,返回 JSOG.parse(responseString).

Currently I make all my requests using a normal get(url, {responseType: 'text'}), and then run the response through RxJs Map Operation to transform the Observable<string> in the Observable that I want, returning JSOG.parse(responseString).

我是否错过了使用某种拦截器的解决方案?非常感谢您的建议.

Did I miss a solution using an Interceptor of some kind? Thanks a lot for your advice.

推荐答案

您只需实现HttpInterceptor并拦截响应,然后根据需要更改正文,然后将其返回给调用者即可.

You can just implement an HttpInterceptor and intercept the response and mutate the body as you wish before it's return to the caller.

我正在做类似的事情,以拦截从我的API返回的Microsoft ASP.NET格式的日期,并将其转换为实际的Date实例.

I'm doing something similar to intercept Microsoft ASP.NET format dates returned from my API and turning them into actual Date instances.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent } from '@angular/common/http';

@Injectable()
export class Interceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(event => {
            if (event instanceof HttpResponse) {
                const resp: HttpResponse<any> = event;

                // Mutate the body, replace ASP.NET Dates with actual local Date objects.
                let body: {} = resp.body;
                this.recurseBody(body);
            }
        });
    }

    private recurseBody(body: {}) {
        if (!body) {
            return;
        }

        for (let key in body) {
            if (body.hasOwnProperty(key)) {
                let element = body[key];
                if (typeof element === 'object') {
                    this.recurseBody(element);
                } else if (typeof element === 'string') {
                    // Check for a MS-format Date with optional TZ offset.
                    const matched = /\/Date\(([-]?\d{1,15})([\+-][01][0-3][0-5][0-9])?\)\//.exec(element);
                    if (matched) {
                        let tzOffsetMs = 0;
                        const tz = matched[2] || '';
                        if (tz) {
                            const hours = parseInt(tz.substr(0, tz.length - 2), 10);
                            const mins = parseInt(tz.substr(tz.length - 2, 2), 10);
                            const tzOffsetMins = mins + hours * 60;
                            tzOffsetMs = tzOffsetMins * 60 * 1000;
                        }

                        // Create a UTC Date object.
                        const date = new Date(+matched[1] + tzOffsetMs);
                        // Get the timezone offset for the local time (in minutes) and convert to ms.
                        const tzOffset = date.getTimezoneOffset() * 60 * 1000;

                        // Create a local date by using the offset
                        const localDate = new Date(date.getTime() + tzOffset);

                        console.log('convert ' + element + ' to ' + date + ' offset ' + date.getTimezoneOffset() + ' local = ' + localDate);

                        // Set the local date.
                        body[key] = localDate;
                    }
                }
            }
        }
    }
}

这篇关于角度httpclient自定义json解析器(jsog)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:37