matrmawi matrmawi - 6 months ago 54
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!";
ob_flush();
flush();
sleep(5);
echo "Ready to run!";


here is my angular2 code:

template: `
<div>
<h3>experimenting!</h3>
<button (click)="callServer()">run the test</button>
<div>the server says: {{msg}}</div>
</div>`
export class AppComponent {
msg:any;
constructor (private http:Http){}
callServer(){
this.http.get("localhost/testing.php")
.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!)


Answer

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

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

and override the BrowserXhr provider with the extended:

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

See this question for more details:

Comments