我似乎没有在从我的 websocket 主机到我的 Angular 2 Observable 的消息中获取 blob 数据

I don't seem to be getting blob data in my message from my websocket host to my Angular 2 Observable

我正在尝试将一些 html/javascript 转换为 Angular 2,但我似乎没有在从我的 websocket 主机到我的 Angular 2 的消息中获取 blob 数据可观察。

来自我的 websocket 主机的消息似乎可以正常发送文本消息,但 blob 消息显示为空对象。

这是我的一些代码:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Component } from '@angular/core';

@Injectable()
export class WebSocketService {
  private websocket: any;
  public sendMessage(text:string){
    this.websocket.send(text);
  }
  public GetInstanceStatus(): Observable<any>{
    this.websocket = new WebSocket("ws://localhost:8080/something");
    return Observable.fromEvent(this.websocket,'message').map(res=>res);
  }
  sendText(json: Object) {
    this.websocket.send(json);
  }
  sendBinary(bytes: any) {
    this.websocket.send(bytes);
  }
}

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  constructor(
    private wss: WebSocketService
  ){
    this.wss.GetInstanceStatus().subscribe((result) => {
      console.log("received: " + result);
      var foo = result.data;
      for(var name in foo) {
        console.log( name + "::" + foo[name] )
      }
    });
  }
}

Blob 数据需要以不同方式解析。 Angular 的 Http 服务 return 是一个 ResponseData 对象,上面有一个 .blob() 方法,但不幸的是还不支持 WebSockets :/

您必须使用 FileReader:

以 old-fashioned 方式解析它
public GetInstanceStatus(): Observable<any>{
var reader = new FileReader();
this.websocket = new WebSocket("ws://localhost:8080/something");

return Observable.fromEvent(this.websocket,'message')
  .map((res) => {
   // logic here for determining if res is a blob based on headers
   // here is what you'd do for a blob though:
   reader.readAsArrayBuffer(res.body)
  });
}

此实现将根据您的负载而有所不同。 readAsArrayBuffer 方法会将数据解析为数组;这可能不是你需要的。查看 FileReader here.

上的 MDN 文档

要点是您将要执行一些映射逻辑以查看是否应将其解析为 blob,然后 return 以这种方式解析。