Lai*_*iso 7 websocket observable rxjs typescript angular
我正在使用Angular 4和websocket创建一个聊天应用程序.为此,我遵循了这个Angular websocket教程
这是WebsocketService源代码:
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable()
export class WebsocketService {
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
})
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的ChatService:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';
const CHAT_URL = 'ws://echo.websocket.org/';
export interface Message {
author: string,
message: string
}
@Injectable()
export class ChatService {
public messages: Subject<Message>;
constructor(wsService: WebsocketService) {
this.messages = <Subject<Message>>wsService
.connect(CHAT_URL)
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return {
author: data.author,
message: data.message
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想检测连接状态.我想知道连接是否已中断或服务器是否已关闭.
为此,我尝试isServerOn()在WebsocketService类中实现一个函数,如下所示:
isServerOn(): Observable<boolean> {
return Observable.of(!!this.subject);
}
Run Code Online (Sandbox Code Playgroud)
但它还没有解决问题.是否有人鼓励同样的问题?
先感谢您.
我建议你在Angular应用程序中使用socket.io-client的类型定义.然后按如下方式定义服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Message } from '../model/message';
import { Event } from '../model/event';
import * as socketIo from 'socket.io-client';
const SERVER_URL = 'https://yourserverhost.com';
@Injectable()
export class SocketService {
private socket;
public initSocket(): void {
this.socket = socketIo(SERVER_URL);
}
public send(message: Message): void {
this.socket.emit('message', message);
}
public onEvent(event: Event): Observable<any> {
return new Observable<Event>(observer => {
this.socket.on(event, () => observer.next());
});
}
}
Run Code Online (Sandbox Code Playgroud)
定义事件枚举:
export enum Event {
CONNECT = 'connect',
DISCONNECT = 'disconnect'
}
Run Code Online (Sandbox Code Playgroud)
然后subscribe从Angular组件到您的服务功能:
export class ChatComponent implements OnInit {
constructor(private socketService: SocketService) { }
ngOnInit(): void {
this.initIoConnection();
}
private initIoConnection(): void {
this.socketService.initSocket();
this.ioConnection = this.socketService.onMessage()
.subscribe((message: Message) => {
this.messages.push(message);
});
this.socketService.onEvent(Event.CONNECT)
.subscribe(() => {
console.log('Connected to the server');
});
this.socketService.onEvent(Event.DISCONNECT)
.subscribe(() => {
console.log('Disconnected');
});
}
}
Run Code Online (Sandbox Code Playgroud)
找到完整的聊天项目,在这里使用Node.js,WebSockets和Angular:https://github.com/luixaviles/socket-io-typescript-chat
我不确定你想实现什么目标
return Observable.of(!!this.subject);
Run Code Online (Sandbox Code Playgroud)
我不认为它会做你认为的那样。相反,你应该创建自己的BehaviorSubject并返回相应的Observable,例如
isServerOn(): Observable<boolean> {
return this.myServerOnSubject.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
在相应的在线/离线代码位置,您可以使用以下命令发出下一个值
this.myServerOnSubject.next(true/false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9535 次 |
| 最近记录: |