import { Component, ElementRef, OnInit, NgZone, Input, Inject } from '@angular/core'; import { NzMessageService } from 'ng-zorro-antd/message'; import signalR from '../../../../signalRChat' import { HttpClient } from '@angular/common/http'; import { StationWeeklyPlanComponent } from '../../task/station-weekly-plan/station-weekly-plan.component'; import { StationTaskExecutionComponent } from '../../task/station-task-execution/station-task-execution.component'; import { HubConnection } from '@microsoft/signalr'; @Component({ selector: 'app-chat-window', templateUrl: './chat-window.component.html', styleUrls: ['./chat-window.component.scss'] }) export class ChatWindowComponent implements OnInit { @Input() public taskId: any;//父组件传进来的任务id static instance: ChatWindowComponent; constructor(private ngZone: NgZone, private element: ElementRef, private message: NzMessageService, @Inject(StationWeeklyPlanComponent) private parentComponent: any, private http: HttpClient, @Inject(StationTaskExecutionComponent) private parentComponent2: any) { } chatcontent userId userName async ngOnInit(): Promise { this.userId = JSON.parse(sessionStorage.getItem('userData')).id this.userName = JSON.parse(sessionStorage.getItem('userData')).name this.chatcontent = this.element.nativeElement.querySelector(`#chatcontent`) setTimeout(() => { this.scrollToBottom() }, 0); await signalR.initSR(this.taskId); await this.getAllMessages(); // 接收来自中心的消息 (signalR.SR as any).on('receiveMessage', (message: any) => { console.log('收到消息', message) this.MessagesList.push(message); if (this.chatcontent.scrollHeight - (this.chatcontent.scrollTop + this.chatcontent.clientHeight) == 0) { setTimeout(() => { this.scrollToBottom() }, 0); } }) } /** * 消息列表 */ members = [] MessagesList = [] isLoading = false chatName = '' /** * 获得所有消息 */ async getAllMessages() { this.isLoading = true console.log('任务id', this.taskId) console.log('this', this) try { this.http.get(`/api/TaskChats/Groups/${this.taskId}`).subscribe((data: any) => { this.MessagesList = data.taskChatMessages || [] this.members = data.members || [] this.members.forEach(item => { this.chatName += item.name + ' ' }) this.chatName = this.chatName + '的群聊' + '(' + this.members.length + ')' this.isLoading = false console.log('chatName', this.chatName) console.log('消息列表', this.MessagesList) setTimeout(() => { this.scrollToBottom() }, 0); }) } catch (error) { console.log(error) } } ngOnDestroy(): void { signalR.stopSR() } text = '' close() { this.parentComponent.closechat() this.parentComponent2.closechat() } send() { if (!this.text) { this.message.create('warning', '输入不能为空'); return } // 发送消息 (signalR.SR as any).send('sendMessage', this.taskId, this.text) setTimeout(() => { this.scrollToBottom() this.text = '' }, 0); } scrollToBottom() { this.chatcontent.scrollTop = this.chatcontent.scrollHeight } }