Angular 8.3.2:WebSocket接收数据后将ArrayBuffer转为Float32Array
Hey Zvika, let's get this conversion sorted out for you! The syntax error you're seeing is likely due to type ambiguity with reader.result (since it can be null, string, or ArrayBuffer) or a small oversight in your code structure. Here's how to fix it properly:
Step 1: Ensure Valid ArrayBuffer and Type Safety
The FileReader.result property has a union type, so we need to confirm it's actually an ArrayBuffer before converting it. Here's your updated code with type checks and proper syntax:
this.wsSubscription = this.webSocket.createObservableSocket("ws://localhost:8080").subscribe(data => { const reader = new FileReader(); reader.readAsArrayBuffer(data); reader.onload = () => { // Assert the result is an ArrayBuffer and check it's not null const arrayBuffer = reader.result as ArrayBuffer; if (arrayBuffer) { // Now safely convert to Float32Array const fArray = new Float32Array(arrayBuffer); console.log("Converted Float32Array:", fArray); // Use fArray for your downstream logic here } else { console.error("Failed to retrieve a valid ArrayBuffer from the FileReader"); } }; });
Step 2: A More Efficient Alternative (Skip FileReader)
Since you're dealing with WebSocket binary data, you can avoid using FileReader entirely by setting the WebSocket's binaryType to 'arraybuffer'. This makes the incoming data directly an ArrayBuffer, simplifying your code:
// For Angular's WebSocket service, configure binaryType during creation this.wsSubscription = this.webSocket.createObservableSocket("ws://localhost:8080", { binaryType: 'arraybuffer' }).subscribe((data: ArrayBuffer) => { const fArray = new Float32Array(data); console.log("Directly converted Float32Array:", fArray); });
This approach is faster because it eliminates the extra FileReader step, and it reduces the chance of type-related errors.
Key Notes:
- Always check that
reader.resultis notnullbefore using it—this prevents runtime crashes if the read operation fails. - Type assertion (
as ArrayBuffer) helps TypeScript recognize the correct type, resolving syntax errors in typed environments like Angular.
内容的提问来源于stack exchange,提问作者Zvi Vered

