All files / sn-client-js/src/HttpProviders RxAjaxHttpProvider.ts

85.71% Statements 18/21
53.85% Branches 7/13
66.67% Functions 2/3
85.71% Lines 18/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45        1x 1x         1x     7x 7x 7x       1x 1x 1x 1x 1x 2x 2x     1x   1x               1x   1x 1x      
/**
 * @module HttpProviders
 *//** */
 
import { Observable, AjaxRequest, Subject } from '@reactivex/rxjs';
import { BaseHttpProvider } from './';
 
/**
 * This is the default RxJs-Ajax based Http calls.
 */
export class RxAjaxHttpProvider extends BaseHttpProvider {
 
    constructor(){
        super();
        this.SetGlobalHeader('content-type', 'application/json; charset=utf-8');
        this.SetGlobalHeader('Accept', 'application/json');
    }
 
    protected AjaxInner<T>(tReturnType, options: AjaxRequest): Observable<T> {
        const sub = new Subject<T>();
        const req = new XMLHttpRequest();
        req.open(options.method || 'GET', options.url || '', true);
        Eif (options.headers){
            for (let headerName in options.headers || []){
                Eif (options.headers[headerName])
                req.setRequestHeader(headerName, options.headers[headerName]);
            }
        }
        req.withCredentials = true; // pass along cookies
 
        req.onload = () => {
            try {
                sub.next(req.responseText && JSON.parse(req.responseText) || null);
            } catch (error) {
                sub.error(error);
            }
        }
 
        req.send(options.body);
 
        req.onerror = sub.error;
        return sub.asObservable();
        // return Observable.ajax(options).map(req => req.response as T).share();
    }
}