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'; @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 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 ngOnInit(): void { 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); this.getAllMessages() signalR.initSR(this.taskId); // 接收来自中心的消息 (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 = '' /** * 获得所有消息 */ getAllMessages() { this.isLoading = true console.log('任务id', this.taskId) this.http.get('/api/TaskChats/Groups', { params: { TaskId: this.taskId, PageNumber: 1, PageSize: 999, SortProperty: 'CreationTime', SortType: 'asc' } }).subscribe((data: any) => { this.MessagesList = data.items[0].taskChatMessages this.members = data.items[0].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); }) } 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 } }