.NET에서 기본 제공 WebSocketSubject
클래스 를 사용하려고합니다 rxjs
. 다음과 같이 대부분의 기본 코드를 Angular 서비스로 설정했습니다.
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { Subscription, from, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebsocketsApiService {
connection: WebSocketSubject<any>;
constructor() {
this.connection = webSocket({
url: <websocket URL>,
closeObserver: {
next: () => console.log('Sockets disconnected.')
},
openObserver: {
next: () => console.log('Socket connected.')
}
});
}
connect(observer: (value: any) => void): Subscription {
return this.connection.subscribe(observer);
}
send(data: any) {
if (this.connection) {
this.connection.next(data);
} else {
console.error('Websockets not connected');
}
}
close() {
if (this.connection) {
this.connection.complete();
this.connection = null;
}
}
ngOnDestroy() {
this.close();
}
}
그러나이 기본 코드를 사용하면 웹 소켓 연결에서 들어오는 모든 데이터를 역 직렬화하지 못합니다. 디버깅 할 때 데이터를으로 수신하고 있다는 것을 알았습니다. 이것이 Blob
기본 deserializer 함수 JSON.parse(data)
가 실패 하는 이유 입니다.
Blob
데이터를 문자열로 가져 와서 간단한 사용자 지정 deserializer 함수를 롤링하려고 시도했지만 Blob.text()
Promise 인 것으로 밝혀졌으며 이것이 제가 갇혀있는 부분입니다.
constructor() {
this.connection = webSocket({
/// ...
deserializer: (e) => e.data.text()
});
}
따라서이 기능을 deserializer로 사용하면이 Websocket 서비스를 구독하는 각 구성 요소가 문자열에 대한 Promise를 가져 오며, 이는 구성 요소에 대한 promise를 해결하는 책임을 연기합니다.
질문 :
당신이 가진 내면의 약속의 값으로 매핑 할 수 있습니다 mergeAll/mergeMap
, concatAll/concatMap
, switchAll/switchMap
. concatAll/concatMap
들어오는 순서대로 값을 내보내고 싶을 것입니다.
constructor() {
this.connection = webSocket({
/// ...
deserializer: (e) => e.data.text()
});
}
connect(observer: (value: any) => void): Subscription {
return this.connection.pipe(
concatAll()
).subscribe(observer);
}
또는
constructor() {
this.connection = webSocket({
/// ...
deserializer: ({data}) => data
});
}
connect(observer: (value: any) => void): Subscription {
return this.connection.pipe(
concatMap(data => data.text())
).subscribe(observer);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다