問題描述
目前在 Angular 2 中是否有一種方法可以使用 angular2/http 模塊檢索 ajax 調用的進度(即完成百分比)?
Is there currently a way within Angular 2 to retrieve the progress (i.e. percentage done) of an ajax call, using the angular2/http module?
我使用以下代碼進行 HTTP 調用:
I use the following code to make my HTTP calls:
let body = JSON.stringify(params);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options)
.timeout(10000, new Error('Timeout exceeded during login'))
.toPromise()
.then((res) => {
...
}).catch((err) => {
...
});
目標是編寫一個同步系統.帖子會返回大量數據,我想告訴用戶同步需要多長時間.
The goal is to write a synchronisation system. The post will return a lot of data, and I want to give the user an indication on how long the syncing will take.
推薦答案
目前(從 v. 4.3.0 開始,當使用來自 @ngular/common/http
HttpClient 時>) Angular 提供開箱即用的監(jiān)聽進度.您只需要創(chuàng)建 HTTPRequest 對象,如下所示:
Currently (from v. 4.3.0, when using new HttpClient
from @ngular/common/http
) Angular provides listening to progress out of the box. You just need to create HTTPRequest object as below:
import { HttpRequest } from '@angular/common/http';
...
const req = new HttpRequest('POST', '/upload/file', file, {
reportProgress: true,
});
當您訂閱請求時,您將在每個進度事件中調用訂閱:
And when you subscribe to to request you will get subscription called on every progress event:
http.request(req).subscribe(event => {
// Via this API, you get access to the raw event stream.
// Look for upload progress events.
if (event.type === HttpEventType.UploadProgress) {
// This is an upload progress event. Compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% uploaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
}
});
更多信息這里.
這篇關于Angular 2 HTTP 進度條的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!