duanlei2458 2016-05-16 21:09
浏览 134
已采纳

angular2 http请求处理响应的chunke

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!)

  • 写回答

2条回答 默认 最新

  • dsa122870 2016-05-16 21:18
    关注

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services