我使用Ionic 4和Angular 8,
我正在尝试在套接字上侦听特定消息,该套接字连接正常,我可以看到客户端很好地接收到该消息,但是观察者从不触发(通知或连接)
此代码可以正常工作,我取消了所有身份验证逻辑,这似乎只是我必须使用promises来获取要提供给套接字的用户凭据的原因(我知道使用查询参数是不好的)
这是实现
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Observer } from 'rxjs';
import * as socketIo from 'socket.io-client';
interface Notification {
unformatedMessage: string;
title: string;
}
// Socket.io events
export enum Event {
CONNECT = 'connect',
DISCONNECT = 'disconnect'
}
@Injectable({
providedIn: 'root'
})
export class NotificationsService{
private socket;
public initSocket(data): void {
this.socket = socketIo("MY_NODE_SERVER", {query: data})
}
public onMessage(): Observable<Notification> {
return new Observable<Notification>(observer => {
this.socket.on('notification', (data: Notification) => {
observer.next(data)});
});
}
public onEvent(event: Event): Observable<any> {
return new Observable<Event>(observer => {
this.socket.on(event, () => observer.next());
});
}
}
然后这样称呼;
ngInit(){
this.authService.getCredentials().then((data)=>{
this.notifications.initSocket(data);
this.notifications.onMessage().subscribe((message: Notification) => {
console.log(message)
});
this.notifications.onEvent(Event.CONNECT).subscribe(() => {
console.log('connected');
});
this.notifications.onEvent(Event.DISCONNECT).subscribe(() => {
console.log('disconnected');
});
});
}