matrmawi matrmawi - 5 months ago 39x
PHP Question

angular2 http requist handling chunke of responses

While I'm experimenting with angular2 a small obstacle came up:

  • I have php code witch returns chunks of responses using "ob_flush".

  • In the front end I successfully made "xhr=XMLHttpRequest" requests and received the responses and handle it using "xhr.onprogress()" and "xhr.onreadystatechange()".

Now when I tried to get the same functionality using angular2 http.get(), I couldn't output the results as they arrive from the server! instead the results are shown by angular at the end of the process after receiving the last response.

I think the rxjs Observer object is buffering the responses!.

So how can I change this behavior?

here is my php code, testing.php:

echo date('H:i:s')." Loading data!";
echo "Ready to run!";

here is my angular2 code:

template: `
<button (click)="callServer()">run the test</button>
<div>the server says: {{msg}}</div>
export class AppComponent {
constructor (private http:Http){}
.subscribe(res=> this.msg= res.text());

When I run this code it shows after 5 seconds:
(19:59:47 Loading data!Ready to run!).

  • It should instantly output: (19:59:47 Loading data!).

  • Then after 5 seconds replaces the previous message with:(Ready to run!)


You need to extend the BrowserXhr class to do that in order to configure the low level XHR object used:

export class CustomBrowserXhr extends BrowserXhr {
  constructor(private service:ProgressService) {}
  build(): any {
    let xhr =;
    xhr.onprogress = (event) => {;
    return <any>(xhr);

and override the BrowserXhr provider with the extended:

bootstrap(AppComponent, [
  provide(BrowserXhr, { useClass: CustomBrowserXhr })

See this question for more details: