Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用angular2 http API跟踪上载/下载进度_Http_Angular_Interceptor_Angular2 Http - Fatal编程技术网

如何使用angular2 http API跟踪上载/下载进度

如何使用angular2 http API跟踪上载/下载进度,http,angular,interceptor,angular2-http,Http,Angular,Interceptor,Angular2 Http,虽然angular2中有很多支持上传/下载进度的临时库,但我不知道如何在上传/下载时使用本机angular2 http api来显示进度 我想使用本机http api的原因是因为我想利用 围绕本机http API的http拦截器(http API包装器),用于验证、缓存和丰富正在发送的实际http请求,例如 此外,angular的http api比任何临时api都更健壮 下面介绍如何使用angular的http api进行上传/下载 但是这篇文章提到,没有一种本土的方式来支持进步 有人试过使用h

虽然angular2中有很多支持上传/下载进度的临时库,但我不知道如何在上传/下载时使用本机angular2 http api来显示进度

我想使用本机http api的原因是因为我想利用

  • 围绕本机http API的http拦截器(http API包装器),用于验证、缓存和丰富正在发送的实际http请求,例如
  • 此外,angular的http api比任何临时api都更健壮
  • 下面介绍如何使用angular的http api进行上传/下载

    但是这篇文章提到,没有一种本土的方式来支持进步

    有人试过使用http api来显示进度吗


    如果没有,您知道angular repo中的一个问题吗?

    我建议使用本机JavaScript XHR包装为可观察的,您可以很容易地自己创建:

    upload(file: File): Observable<string | number> {
    
        let fd: FormData = new FormData();
    
        fd.append("file", file);
    
        let xhr = new XMLHttpRequest;
    
        return Observable.create(observer => {
    
            xhr.addEventListener("progress", (progress) => {
    
                let percentCompleted;
    
                // Checks if we can really track the progress
                if (progress.lengthComputable) {
    
                    // progress.loaded is a number between 0 and 1, so we'll multiple it by 100
                    percentCompleted = Math.round(progress.loaded / progress.total * 100);
    
                    if (percentCompleted < 1) {
                        observer.next(0);
                    } else {
                        // Emit the progress percentage
                        observer.next(percentCompleted);
                    }
                }
            });
    
            xhr.addEventListener("load", (e) => {
    
                if (e.target['status'] !== 200) observer.error(e.target['responseText']);
    
                else observer.complete(e.target['responseText']);
            });
    
            xhr.addEventListener("error", (err) => {
    
                console.log('upload error', err);
    
                observer.error('Upload error');
            });
    
            xhr.addEventListener("abort", (abort) => {
    
                console.log('upload abort', abort);
    
                observer.error('Transfer aborted by the user');
            });
    
            xhr.open('POST', 'http://some-dummy-url.com/v1/media/files');
    
            // Add any headers if necessary
            xhr.setRequestHeader("Authorization", `Bearer rqrwrewrqe`);
    
            // Send off the file
            xhr.send(fd);
    
            // This function will get executed once the subscription
            // has been unsubscribed
            return () => xhr.abort()
        });
    }
    

    我建议将本机JavaScript XHR包装为一个可观察对象,您可以很容易地自己创建:

    upload(file: File): Observable<string | number> {
    
        let fd: FormData = new FormData();
    
        fd.append("file", file);
    
        let xhr = new XMLHttpRequest;
    
        return Observable.create(observer => {
    
            xhr.addEventListener("progress", (progress) => {
    
                let percentCompleted;
    
                // Checks if we can really track the progress
                if (progress.lengthComputable) {
    
                    // progress.loaded is a number between 0 and 1, so we'll multiple it by 100
                    percentCompleted = Math.round(progress.loaded / progress.total * 100);
    
                    if (percentCompleted < 1) {
                        observer.next(0);
                    } else {
                        // Emit the progress percentage
                        observer.next(percentCompleted);
                    }
                }
            });
    
            xhr.addEventListener("load", (e) => {
    
                if (e.target['status'] !== 200) observer.error(e.target['responseText']);
    
                else observer.complete(e.target['responseText']);
            });
    
            xhr.addEventListener("error", (err) => {
    
                console.log('upload error', err);
    
                observer.error('Upload error');
            });
    
            xhr.addEventListener("abort", (abort) => {
    
                console.log('upload abort', abort);
    
                observer.error('Transfer aborted by the user');
            });
    
            xhr.open('POST', 'http://some-dummy-url.com/v1/media/files');
    
            // Add any headers if necessary
            xhr.setRequestHeader("Authorization", `Bearer rqrwrewrqe`);
    
            // Send off the file
            xhr.send(fd);
    
            // This function will get executed once the subscription
            // has been unsubscribed
            return () => xhr.abort()
        });
    }
    

    从Angular 4.3.x及更高版本开始,可以使用新的
    @Angular/common/http
    实现

    阅读本节

    简单上传示例(从上述章节复制):

    对于下载,它可能类似于:

    const req = new HttpRequest('GET', '/download/file', {
      reportProgress: true,
    });
    
    http.request(req).subscribe(event => {
      // Via this API, you get access to the raw event stream.
      // Look for download progress events.
      if (event.type === HttpEventType.DownloadProgress) {
        // This is an download progress event. Compute and show the % done:
        const percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`File is ${percentDone}% downloaded.`);
      } else if (event instanceof HttpResponse) {
        console.log('File is completely downloaded!');
      }
    });
    

    请记住,如果您正在监视下载,则必须设置
    内容长度,否则无法测量请求。

    从Angular 4.3.x及更高版本开始,可以使用新的from
    @Angular/common/http
    实现

    阅读本节

    简单上传示例(从上述章节复制):

    对于下载,它可能类似于:

    const req = new HttpRequest('GET', '/download/file', {
      reportProgress: true,
    });
    
    http.request(req).subscribe(event => {
      // Via this API, you get access to the raw event stream.
      // Look for download progress events.
      if (event.type === HttpEventType.DownloadProgress) {
        // This is an download progress event. Compute and show the % done:
        const percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`File is ${percentDone}% downloaded.`);
      } else if (event instanceof HttpResponse) {
        console.log('File is completely downloaded!');
      }
    });
    

    请记住,如果您正在监视下载,则必须设置
    内容长度,否则无法测量请求。

    现在可以了,请检查


    我可以在这里举个例子,但我认为Angular docs的官方例子会更好

    这现在是可能的,请查看



    我可以在这里举个例子,但我认为Angular docs的官方例子会更好

    有人要求结束这个问题,说它太宽泛了。嗯,不是。有人使用angular的http api跟踪进度吗?。任何通用Http API都应该在这个上下文中使用。这是一个非常具体的问题。有人要求结束这个问题,说它太宽泛了。嗯,不是。有人使用angular的http api跟踪进度吗?。任何通用Http API都应该在这个上下文中使用。这是一个非常具体的问题。写我自己的版本是我想要避免的事情&我已经在问题中提到了为什么会这样,例如,你的例子根本没有处理退订问题。除此之外,我还将失去在发送请求之前以各种方式验证和丰富请求的拦截功能。您不需要取消订阅我的代码示例。我们在所有
    XHR
    事件中调用
    complete
    error
    ,它们将自动取消订阅。请详细说明验证和充实请求的含义。Angular的http目前不提供此功能,请看。有
    bytesload
    totalBytes
    ,但这还没有在任何地方使用过。看看这个。w、 r.t complete/error,如果用户在发送请求时单击其他选项卡(可能是应用程序将此行为设置为自然行为),则会提示用户取消现有请求并转到单击的页面。在这种情况下,你需要取消订阅写我自己的版本是我想要避免的&我已经在问题中提到了为什么会这样,例如,你的例子根本不处理取消订阅。除此之外,我还将失去在发送请求之前以各种方式验证和丰富请求的拦截功能。您不需要取消订阅我的代码示例。我们在所有
    XHR
    事件中调用
    complete
    error
    ,它们将自动取消订阅。请详细说明验证和充实请求的含义。Angular的http目前不提供此功能,请看。有
    bytesload
    totalBytes
    ,但这还没有在任何地方使用过。看看这个。w、 r.t complete/error,如果用户在发送请求时单击其他选项卡(可能是应用程序将此行为设置为自然行为),则会提示用户取消现有请求并转到单击的页面。在这种情况下,你需要取消订阅我在4.1.x上的工作以及你确定它是4.1.x?不仅在
    package.json
    中,而且获取的是上面的?嗨,我正在获取未定义的event.total不知道为什么?@slartidan
    import{HttpClient}from'@angular/common/http'
    constructor(私有http:HttpClient)
    我可以补充一点,当使用Angular
    7.2.4
    时,我需要同时使用
    reportProgress:true
    observe:'events'
    来实际查看进度事件。只有
    observe:“events”
    不会下载/上传进度事件,而省略
    observe
    将默认为
    observe:“body”
    ,它只返回响应的正文,不返回其他事件。在4.1.x上为我工作过,你确定它是4.1.x吗?不仅在
    package.json
    中,而且获取的是上面的?嗨,我正在获取未定义的event.total不知道为什么?@slartidan
    import{HttpClient}from'@angular/common/http'
    构造函数(私有http:HttpClient)
    我可以补充一点,当使用Angular
    7.2.4
    时,我需要两个
    报告进度:true