Spaces:
Running
Running
import { Component, OnDestroy } from '@angular/core'; | |
import { CommonModule } from '@angular/common'; | |
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; | |
import { MatButtonModule } from '@angular/material/button'; | |
import { MatIconModule } from '@angular/material/icon'; | |
import { MatFormFieldModule } from '@angular/material/form-field'; | |
import { MatInputModule } from '@angular/material/input'; | |
import { MatCardModule } from '@angular/material/card'; | |
import { Subscription } from 'rxjs'; | |
import { ApiService } from '../services/api.service'; | |
interface ChatMessage { | |
author: 'user' | 'assistant'; | |
text: string; | |
} | |
({ | |
selector: 'app-chat', | |
standalone: true, | |
imports: [ | |
CommonModule, | |
ReactiveFormsModule, | |
MatButtonModule, | |
MatIconModule, | |
MatFormFieldModule, | |
MatInputModule, | |
MatCardModule | |
], | |
templateUrl: './chat.component.html', | |
styleUrls: ['./chat.component.scss'] | |
}) | |
export class ChatComponent implements OnDestroy { | |
/** Backend’ten dönen oturum kimliği */ | |
sessionId: string | null = null; | |
/** Sohbet geçmişi */ | |
messages: ChatMessage[] = []; | |
/** Kullanıcı metni */ | |
input = this.fb.control('', Validators.required); | |
/** Arkaplan istekleri için abonelikleri tutuyoruz */ | |
private subs = new Subscription(); | |
constructor(private fb: FormBuilder, private api: ApiService) {} | |
/** <Start Chat> butonu */ | |
startChat(): void { | |
const sub = this.api.startChat().subscribe({ | |
next: (res: any) => { | |
this.sessionId = res.session_id; | |
}, | |
error: () => { | |
alert('Chat başlatılamadı - tekrar deneyin.'); | |
} | |
}); | |
this.subs.add(sub); | |
} | |
/** <Send> butonu */ | |
send(): void { | |
if (!this.sessionId || this.input.invalid) return; | |
const text = this.input.value!.trim(); | |
if (!text) return; | |
// Önce kullanıcı mesajını ekranda göster | |
this.messages.push({ author: 'user', text }); | |
this.input.reset(); | |
const sub = this.api.chat(this.sessionId, text).subscribe({ | |
next: (res: any) => { | |
this.messages.push({ author: 'assistant', text: res.text }); | |
}, | |
error: () => { | |
this.messages.push({ | |
author: 'assistant', | |
text: '❗️ Mesaj iletilemedi, lütfen tekrar deneyin.' | |
}); | |
} | |
}); | |
this.subs.add(sub); | |
} | |
ngOnDestroy(): void { | |
this.subs.unsubscribe(); | |
} | |
} | |