Angular的报告进度和PHP。一个请求,多个响应。可能吗?



我有一个php文件,它在提交表单时处理后端的多个请求,因为这需要一些时间,我想通知用户进度,在php执行过程中显示一些通知,直到最终响应到达。从php发送的消息如下所示:

$text = 'Getting time from server...';
$data = ['message' => $text];
echo json_encode($data);
...
...
...
$text = 'Server Time is ' . $syncTime;
$data = ['message' => $text];
echo json_encode($data);

这是驻留在服务上的Http请求:

getResult(): Observable<HttpEvent<any>> {
const url = `${this.PHP_API_SERVER}/getResult.php`;
return this.http.get(url, {
responseType: "json",
reportProgress: true,
observe: "events",
headers: new HttpHeaders({ "Content-Type": "application/json" })
});
}

在组件上,我订阅了上述可观察到的:

onSubmit() {
this.dbQuery
.getResult()
.pipe(takeUntil(this._destroy))
.subscribe((event: HttpEvent<any>) => {
if (event.type === HttpEventType.DownloadProgress) {
console.log("download progress", event);
}
if (event.type === HttpEventType.Response) {
console.log("donwload completed", event);
}
});
}

有了这个,我可以在控制台上看到几个事件对象,看起来像这样:

Object { type: 3, loaded: 57 } Object { type: 3, loaded: 164 }

但是我没有得到php发送的实际消息。

最后,请求返回一个错误消息Http failure during parsing for http://127.0.0.1/backend/getResult.php

有人知道我应该怎么做才能从服务器获得实际的JSON响应吗?任何帮助都将不胜感激。。。

经过一段时间的实验和一些更改,我能够通过将responseTypejson更改为text来从服务器获得响应。我想出了以下办法。

在服务器端,我在消息之间添加了一个分隔符,所以现在我有了这个

$text = 'Getting time from server...';
$data = ['message' => $text];
echo json_encode($data);
echo "|";

我的请求现在看起来是这样的:

getResult(): Observable<HttpEvent<any>> {
const url = `${this.PHP_API_SERVER}/getResult.php`;
return this.http.get(url, {
responseType: "text",
reportProgress: true,
observe: "events",
headers: new HttpHeaders({ "Content-Type": "text/plain" })
});
}

这就是我如何处理接收到的数据

onSubmit() {
this.dbQuery
.getResult()
.pipe(takeUntil(this._destroy))
.subscribe((event: HttpEvent<any>) => {
if (event.type === HttpEventType.DownloadProgress) {
//get the partialText property of the received event
const partialText = (<HttpDownloadProgressEvent>(event)).partialText;
//split the received text on '|' and filter empty elements 
let textArray: string[] = partialText.split("|").filter(x => x);
//array size
this.totalLength = textArray.length;
//take the last element of the string array
let responseTxt = textArray[this.totalLength - 1];
//convert it to an object
let res = JSON.parse(responseTxt);
console.log("response: ", res);
});
}

所以现在我有了来自后台的流式响应。

最新更新