Angular 4中的WebSocket
我正在用Angular 4和websocket创建聊天应用程序。对于这一点,我已经按照这个Angular websocket tutorialAngular 4中的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);
}
}
而且这是我的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
}
});
}
}
它工作正常,但我想检测连接状态。我想知道连接是否中断或服务器是否关闭。
对于这一点,我试图实现WebsocketService
类内的isServerOn()
功能是这样的:
isServerOn(): Observable<boolean> { return Observable.of(!!this.subject);
}
但一直没有解决问题。有没有人惹过同样的问题?
预先感谢您。
回答:
我不知道你想与
return Observable.of(!!this.subject);
实现我不认为它做什么,你认为它做什么。 相反,你应该宁可创建自己的BehaviorSubject并返回 对应的可观测像
isServerOn(): Observable<boolean> { return this.myServerOnSubject.asObservable();
}
在相应的在线/离线码位置,可以随后与
this.myServerOnSubject.next(true/false);
回答:
发出的下一个值,我建议你使用您的Angular应用程序中的socket.io-client的类型定义。从您的角度成分
export enum Event { CONNECT = 'connect',
DISCONNECT = 'disconnect'
}
然后subscribe
到您的服务功能:
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());
});
}
}
定义事件枚举:然后如下定义服务
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');
});
}
}
找到完整的聊天项目,这里使用的是Node.js,WebSockets和Angular:https://github.com/luixaviles/socket-io-typescript-chat
以上是 Angular 4中的WebSocket 的全部内容, 来源链接: utcz.com/qa/263566.html