我的signalr連接的客戶沒有收到訊息。 我的Chathub:
public class Chathub : Hub
{
private readonly string _botUser;
private readonly string _globalRoom;
公共Chathub()
{
_botUser = "My Chatbot";
_globalRoom = "大廳"。
}
public async Task Join(string message)
{
//等待 Groups.AddToGroupAsync(Context.ConnectionId, _globalRoom)。
//await Clients.Group(_globalRoom).SendAsync("ReceiveMessage", $"{_botUser} : Welcome {message}" )。
await Clients.All.SendAsync("ReceiveMessage", $"{_botUser} : Welcome {Context.ConnectionId}"); //Checking connectionid
//await Clients.All.SendAsync("ReceiveMessage", $"{_botUser} : Welcome {message}")。
}
}
我已經在SharedService中定義了我的hubconnection:
export class SharedService {
public readonly URL = "https://localhost:44333/";
private hubConnection: HubConnection;
messageModel: Message = {
message: null
}
constructor(private http: HttpClient) {
this.BuildConnection();
this.StartConnection();
this.JoinMessage()。
}
public BuildConnection = () => {
this.hubConnection = new HubConnectionBuilder().withUrl('/chathub').build()。
}
公共StartConnection = () => {
this.hubConnection.start()
.then(() => console.log("Connection started...."))
.catch(err => console.log(err))。
}
LoginUser(UserModel: User): 觀察<用戶> {
this.hubConnection.invoke("Join", UserModel.userName)。
return this.http.post<User> (this.URL "Account/LoginUser", UserModel);
}
JoinMessage()。Observable<string> {
this.hubConnection.on("ReceiveMessage", (messages) => {
this.messageModel.message = messages;
});
return of(this.messageModel.message)。
}
我有兩個組件。一旦用戶登錄,hubconnection就被啟動,并被路由到另一個顯示歡迎資訊的組件。 訊息的顯示方式是這樣的
export class MainPageComponent implements OnInit {
public messages = [];
constructor(public service: SharedService) {}.
ngOnInit() {
this.DisplayMessage()。
}
public DisplayMessage() {
this.service.JoinMessage().subscribe((data) => this.messages.push(data))。
}
}
當我打開兩個標簽并登錄時,這兩個標簽之間不共享歡迎資訊。第一個登錄的客戶端沒有收到歡迎第二個客戶端的訊息。我認為chathub中的connectionId應該是相同的,以便兩個客戶端可以相互通信,但它是不同的。
uj5u.com熱心網友回復:
你需要在訂閱時回傳正確的Observable(不要在這里使用of(),使用Subject.next()代替)
private message$: Subject<any> = new Subject();
JoinMessage(): Observable<string> {
this.hubConnection.on("ReceiveMessage", (mages) => {
this.message$.next(messages)。
});
return this.message$.asObservable()。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311776.html
標籤:
