Friday, October 20, 2017

Intercept each http calls an ES6 approach

I wanted to write injectable service in Angular which can intercept all ajax calls. Basically before ajaxStart and after after finished. I am able to achieve by this code-snippets. But I am able to achieve it using es5 syntax. How I can do the same thing by extending XMLHttpRequest which is shown in file no: 3?

1) http-interceptor.ts

import { Injectable, Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

interface AjaxRequest {
    url?: string;
    requestCount?: number;
    method?: string;
}

interface AjaxResponse {
    url?: string;
    requestCount?: number;
    response?: string;
}

@Injectable()
export class HttpInterceptor {

    public ajaxStart = new BehaviorSubject<AjaxRequest>({});
    public ajaxStop = new BehaviorSubject<AjaxResponse>({});

    constructor() {
        this.bootstrapAjaxInterceptor();
    }

    private bootstrapAjaxInterceptor() {

        const _self = this;
        const originalOpen = XMLHttpRequest.prototype.open;

        XMLHttpRequest.prototype.open = function (xhrMethod, requestUrl) {

            _self.ajaxStart.next(requestUrl);

            this.addEventListener('readystatechange', xhr => {

                _self.ajaxStop.next(this.responseURL);

            }, false);

            originalOpen.apply(this, arguments);
        };
    }
}

2) app-component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

    constructor(private httpInterceptor: HttpInterceptor) { }

    ngOnInit() {

        this.httpInterceptor.ajaxStart.subscribe(url => {
            console.log('ajaxStart : ', url);
        });

        this.httpInterceptor.ajaxStop.subscribe(url => {
            console.log('ajaxStop : ', url);
        });
    }
}

3) http-interceptor.ts

@Injectable()
export class HttpInterceptor extends XMLHttpRequest {

    open(xhrMethod, requestUrl) {
        // Equivalent to XMLHttpRequest.prototype.open
        // Now how to handle `readystatechange`
    }

    ajaxStart() { }

    ajaxStop() { }
}

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/20/intercept-each-http-calls-an-es6-approach/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment