Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello. I am having some problems switching from XHRBackend and XHRConnection (Angular 4.3) to Angular 11. I know I have to use an HttpInterceptor or/and HttpXhrBackend, but I can't figure out how to apply it to in a project.

custom.http.ts
JavaScript
export class CustomXHRBackend extends XHRBackend {
   
   constructor(private browserXHR: BrowserXhr,
        
      private baseResponseOptions: ResponseOptions,
 private xsrfStrategy: XSRFStrategy, private eventsService: EventsService) {
        
         super(browserXHR, baseResponseOptions, xsrfStrategy);
    
   }
    
   createConnection(request: Request) {
        
      this.xsrfStrategy.configureRequest(request);
        
      let conn = new CustomXHRConnection(request, this.browserXHR, 
      this.baseResponseOptions, this.eventsService);
        
      return conn;
    
   }


}


@Injectable()
export class CustomXHRConnection extends XHRConnection {
    getResponseUrl(xhr){
        if ('responseURL' in xhr){
            return xhr.responseURL;
        }
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
            return xhr.getResponseHeader('X-Request-URL');
        }
        return;
    }    
        
    
    setDetectedContentType(req, _xhr) {
        super.setDetectedContentType(req, _xhr);
    }
    //--only for _xhr.upload.onprogress
    constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions: ResponseOptions, private eventsService: EventsService) {
        super(req, browserXHR, baseResponseOptions);
        let _setDetectedContentType = super.setDetectedContentType;
        let _self = this;
        this.response = new Observable(function (responseObserver) {
            var _xhr = browserXHR.build();
            let file = req.headers.get("upload-file");
            if (file) {
                req.headers.delete('upload-file');
                _xhr.open(RequestMethod[req.method].toUpperCase(), req.url, true);
            }
            else {
                _xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
            }

            if (req.withCredentials != null) {
                _xhr.withCredentials = req.withCredentials;
            }
            var onLoad = function () {
                var status = _xhr.status === 1223 ? 204 : _xhr.status;
                var body = null;
                if (status !== 204) {
                    body = (typeof _xhr.response === 'undefined') ? _xhr.responseText : _xhr.response;
                    if (typeof body === 'string') {
                        body = body.replace(XSSI_PREFIX, '');
                    }
                }
                if (status === 0) {
                    status = body ? 200 : 0;
                }
                var headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
                var url = _self.getResponseURL(_xhr) || req.url;
                var statusText = _xhr.statusText || 'OK';
                var responseOptions = new ResponseOptions({ body: body, status: status, headers: headers, statusText: statusText, url: url });
                if (baseResponseOptions != null) {
                    responseOptions = baseResponseOptions.merge(responseOptions);
                }
                var response = new Response(responseOptions);
                response.ok = (status >= 200 && status < 300);
                if (response.ok) {
                    responseObserver.next(<any>response);
                    responseObserver.complete();
                    return;
                }
                responseObserver.error(response);
            };
            // error event handler
            var onError = function (err) {
                var responseOptions = new ResponseOptions({
                    body: err,
                    type: ResponseType.Error,
                    status: _xhr.status,
                    statusText: _xhr.statusText,
                });
            if (baseResponseOptions != null) {
                responseOptions = baseResponseOptions.merge(responseOptions);
            }
            responseObserver.error(new Response(responseOptions));
            };
            _setDetectedContentType(req, _xhr);
            if (req.headers == null) {
                req.headers = new Headers();
                }
            if (!req.headers.has('Accept')) {
                req.headers.append('Accept', 'application/json, text/plain, */*');
            }
            req.headers.forEach(function (values, name) { return _xhr.setRequestHeader(name, values.join(',')); });
            // Select the correct buffer type to store the response
            if (req.responseType != null && _xhr.responseType != null) {
                switch (req.responseType) {
                    case ResponseContentType.ArrayBuffer:
                        _xhr.responseType = 'arraybuffer';
                        break;
                    case ResponseContentType.Json:
                        _xhr.responseType = 'json';
                        break;
                    case ResponseContentType.Text:
                        _xhr.responseType = 'text';
                        break;
                    case ResponseContentType.Blob:
                        _xhr.responseType = 'blob';
                        break;
                    default:
                        throw new Error('The selected responseType is not supported');
                    }
            }
            _xhr.addEventListener('load', onLoad);
            _xhr.addEventListener('error', onError);
            if (file) {
                _xhr.upload.onprogress = (e) => {
                    if (e.lengthComputable) {                   
                        eventsService.addEvent("upload_progress", {
                            "percent": Math.round(e.loaded / e.total * 100),
                            "file": file 
                        });
                    }
                };
                _xhr.upload.onload = (e) => {
                    eventsService.addEvent("upload_progress", { "percent": 100, "file": file })
                }
            }
            _xhr.send(req.getBody());

            return function() {
                _xhr.removeEventListener('load', onLoad);
                _xhr.removeEventListener('error', onError);
                _xhr.abort();
            };
        });
    }   
}



And use it in AppModule
app.module.ts
export function _customXHRBackend(browserXHR: BrowserXhr, baseResponseOptions: ResponseOptions, xsrfStrategy: XSRFStrategy, eventsService: EventsService): XHRBackend {
    return new CustomXHRBackend(browserXHR, baseResponseOptions, xsrfStrategy, eventsService);
};


@NgModule({
    imports: [],

    providers: [
        {
            provide: XHRBackend,
            useFactory: _customXHRBackend, 
            deps: [BrowserXhr, ResponseOptions, XSRFStrategy, EventsService]
        },     
    ],
   
    bootstrap: [MainApp]
})
export class AppModule {
}


What I have tried:

I started using HttpInterceptor instead this, but still can't figure it out. How i can use it?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900