gpt4 book ai didi

Angular 2 跨组件共享 websocket 服务

转载 作者:太空狗 更新时间:2023-10-29 17:33:12 26 4
gpt4 key购买 nike

我正在使用 Angular 2 构建一个 Web 应用程序,我希望在其中让多个组件监听同一服务。该服务返回一个 observable,该 observable 返回来自 websocket 的传入数据。我根据 this 编写了代码例子。

目前的问题是:数据通过服务从主组件发送到服务器(使用 websockets)并返回数据。但是,只有 home.component 中的观察者被调用(id:room.created 和数据),而不是导航栏中的观察者。

有人能告诉我为什么不同时调用两者吗?我还尝试将 messages$.subscribe 添加到 app.component 但无济于事。

现在,让我们来看代码。

返回可观察对象的消息服务。组件使用此服务发送和接收消息。

@Injectable()
export class MessageService {
private _messages: Rx.Subject<Message>;
messages$: Rx.Observable<Message>;

constructor(wsService: SocketService, private configuration: Configuration) {
console.log('messag eservice');
this._messages = <Rx.Subject<Message>>wsService
.connect()
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return {
id: data.id,
data: data.data,
}
});

this.messages$ = this._messages.asObservable();
}

public send(message: Message): void {
this._messages.next(message);
}
}

创建 websocket 连接并将自身绑定(bind)到此套接字的输入和输出的套接字服务。

import { Injectable } from '@angular/core';
import * as Rx from "rxjs/Rx";
import { Configuration } from '../app.constants';

@Injectable()
export class SocketService {
private subject: Rx.Subject<MessageEvent>;

constructor(private configuration: Configuration){};

public connect(wsNamespace = ''): Rx.Subject<MessageEvent> {
var url = this.configuration.wsUrl + wsNamespace;
if(!this.subject) {
this.subject = this.create(url);
}
return this.subject;
}

private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);

// bind ws events to observable (streams)
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);
});

// on obs next (send something in the stream) send it using ws.
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
},
};

return Rx.Subject.create(observer, observable);
}
}

具有以下提供程序的应用程序组件:

  providers: [MessageService, SocketService, Configuration, AuthService]

我正在我的主 app.component 中实例化提供者,以确保消息和套接字服务不会被实例化两次。

我的 home.component 看起来像这样(这是一个使用路由加载的页面):

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { Router } from '@angular/router';
import { MessageService } from '../../services/message.service';

@Component({
...
providers: []
})
export class HomeComponent implements OnInit {
constructor(private router: Router, private messageService: MessageService) {}

ngOnInit(): void {
this.messageService.send({
id: 'room.create',
data: {'name': 'Blaat'}
});

this.messageService.messages$.subscribe(msg => {
console.log(msg);
if(msg.id == 'room.created') {
// navigate naar games!
}
});
}

}

我的导航栏组件看起来像这样(指令):

import { Component, OnInit } from '@angular/core';
import { MessageService } from '../../services/message.service';

@Component({
moduleId: module.id,
selector: 'navbar',
templateUrl: 'navbar.component.html',
styleUrls: ['navbar.component.css']
})
export class Navbar implements OnInit {

constructor(private messageService: MessageService) { }

ngOnInit() {

this.messageService.messages$.subscribe(msg => {
console.log(msg);
if(msg.id == 'room.created') {
// navigate naar games!
}
});
}

}

最佳答案

您的可观察创建函数似乎被多次调用,很可能是两个组件 => 两个订阅 => 两个可观察创建函数调用。所以最新的 observable create fn 覆盖了之前的 observable 对 websocket onmessage、onerror 和 onclose 的回调。您应该多播底层可观察对象以防止这种情况发生(共享运算符应该可以解决问题)。

        // bind ws events to observable (streams)
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);
}).share();

有关如何正确执行此操作的更多有用资源 https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts https://github.com/blesh/RxSocketSubject

关于Angular 2 跨组件共享 websocket 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com