我以某种角度使用了此代码,但并没有真正理解它,因为我在网站上看到了它:
创建了两个服务,分别称为WebSocket Service和NewsFeed
我知道这听起来很疯狂,但请忍受我。
我不了解的重要地方包括:
Rx.Subject<MessageEvent>
观察者和可观察者如何在此处操作
本质上,我正在尝试使用WebSockets创建NewsFeed
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs/Rx';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
// Socket Connection
private socket;
constructor() { }
connect(): Rx.Subject<MessageEvent> {
this.socket = io('http://localhost:3000');
/** Define Observable which will observe any incoming messages
from socket.io server */
let observable = new Observable(observer => {
this.socket.on('message',(data) => {
console.log('Recieved message from Websocket Server')
observer.next();
})
return () => {
this.socket.disconnect();
}
});
// We define our Observer which will listen to messages
// from our other components and send messages back to our
// socket server whenever the `next()` method is called.
let observer = {
next: (data: Object) => {
this.socket.emit('message',JSON.stringify(data));
}
};
// Return Rx.Subject which is a combination of both an observable and observer
return Rx.Subject.create(observer,observable);
}
}
新闻订阅服务
import { Injectable } from '@angular/core';
import { WebSocketService } from './web-socket.service';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NewsFeedService {
feeds: Subject<any>;
constructor(private wsService: WebSocketService) {
this.feeds = <Subject<any>>wsService
.connect()
.map((response: any): any => {
return response;
})
}
sendMsg(msg){
this.feeds.next(msg);
}
}