add websocket

This commit is contained in:
pakintada@gmail.com 2023-10-03 11:45:08 +07:00
parent f787b6ade3
commit b25c836f0c
2 changed files with 64 additions and 0 deletions

View file

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { WebsocketService } from './websocket.service';
describe('WebsocketService', () => {
let service: WebsocketService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(WebsocketService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View file

@ -0,0 +1,48 @@
import { Injectable } from '@angular/core';
import { Observable, filter, share } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
private subject!: WebSocketSubject<unknown>;
private res: any;
constructor() {}
public connect(url: string){
this.subject = webSocket(url);
this.subject.subscribe({
next: (msg: any) => {
// console.log("message", msg);
this.res = msg;
console.log("res set =",this.res);
},
error: (err: any) => {
console.error(err);
},
complete: () => {
console.log('complete');
}
})
}
// public listenTo<T>(topic: string): Observable<T> {
// return this.subject.pipe(
// value => value.topic == topic,
// );
// }
public data = this.subject.pipe(
share()
);
public send(url: any){
this.subject.next(url);
}
}