在Obhrable中的xhr.send()之后获取服务器响应 [英] Getting the server response after xhr.send() in an Observable

查看:99
本文介绍了在Obhrable中的xhr.send()之后获取服务器响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一种在Angular 2应用程序中发布文件的方法.它基于我在此处找到的解决方案.

I implemented a method to POST a file in my Angular 2 app. It is based on the solution I found here.

由于Angular 2本身不支持文件上传,因此该解决方案必须利用xhr.工作解决方案如下所示:

Because Angular 2 doesn't support file uploads by itself, the solution has to leverage xhr. This is what the working solution looks like:

组件方法:

onSubmit(): void {
    this.inputModuleService.postFile(this.files).subscribe(() => {
        console.log('sent');
    });
}

服务方法:

postFile (files: File[]): Observable<string> {
    var url = this.uploadURL;

    return Observable.create(observer => {
        var formData: FormData = new FormData()
        var xhr: XMLHttpRequest = new XMLHttpRequest();

        formData.append("upload", files[i], files[i].name);

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    observer.next(JSON.parse(xhr.response));
                    observer.complete();
                } else {
                observer.error(xhr.response);
                }
            }
        };

        xhr.open('POST', url, true);
        xhr.send(formData);
    });
}

我的问题是,在调用xhr.send()之后,我不理解如何将响应返回给onSubmit()方法. Angular2以及可观察和可承诺的概念对我来说都是新的.

My issue is that I don't understand how to get the response back to the onSubmit() method after the call to xhr.send(). Angular2 and the concept of observables and promises are all new to me.

如何从这个可观察到的位置获得服务器的响应?

How can I get the server's response from this observable?

推荐答案

服务器响应提供给subscribe()的成功和错误回调:

The server response is provided to the success and error callbacks of subscribe():

onSubmit(): void {
    this.inputModuleService.postFile(this.files).subscribe(
      response => {
          //response is the server's response, parsed into a javascript object
          console.log('server responded: ', response);
      },
      error => {
          //server response emitted when xhr.status !== 200
          console.error(error);
      }
   );
}

此行:

formData.append("upload", files[i], files[i].name);

将抛出错误,因为i未定义.您从中复制的代码在循环中包含了该行,而i是当前索引.在您的代码中不是这种情况.

Will throw errors because i is undefined. The code you copied from had that line within a loop and i was the current index. That's not the case in your code.

您的函数声明:

postFile (files: File[]): Observable<string>

应更改为

postFile (files: File[]): Observable<any>

因为postFile返回的Observable发出对象,而不是字符串.

Because the Observable returned by postFile emits objects, not strings.

如果您打算仅上传一个文件,则还应该将files: File[]更改为file: File并在文件后附加:

If you mean to upload just one file, you should also change files: File[] to file: File and append the file with:

formData.append("upload", file, file.name);

这篇关于在Obhrable中的xhr.send()之后获取服务器响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆