tab2.page.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // src/app/tab2/tab2.page.ts
  2. import { Component, OnInit } from '@angular/core';
  3. import { HttpClient } from '@angular/common/http';
  4. @Component({
  5. selector: 'app-tab2',
  6. templateUrl: './tab2.page.html',
  7. styleUrls: ['./tab2.page.scss'],
  8. })
  9. export class Tab2Page implements OnInit {
  10. messages: any[] = [];
  11. userInput: string = '';
  12. isLoading: boolean = false;
  13. constructor(private http: HttpClient) {}
  14. ngOnInit() {
  15. // 页面加载时自动发送一条随机的欢迎消息
  16. const welcomeMessages = [
  17. '我是您的AI医生小爱,有什么可以帮到您的吗?',
  18. '今天天气不错,可以出去散步哦。',
  19. '您好!我是您的健康助手,有什么我可以帮助您的吗?',
  20. '很高兴见到您!请告诉我您需要什么帮助。',
  21. '欢迎您!请问有什么健康方面的问题需要咨询吗?'
  22. ];
  23. const randomMessage = welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];
  24. this.sendMessageFromAI(randomMessage);
  25. }
  26. sendMessage() {
  27. if (this.userInput.trim() === '') return;
  28. this.messages.push({ text: this.userInput, sender: 'user' });
  29. this.isLoading = true;
  30. this.userInput = '';
  31. // 发送请求到 AI 服务
  32. this.http.post('https://your-ai-service-endpoint.com/api/chat', { message: this.userInput })
  33. .subscribe((response: any) => {
  34. this.messages.push({ text: response.message, sender: 'ai' });
  35. this.isLoading = false;
  36. }, (error) => {
  37. console.error('Error:', error);
  38. this.messages.push({ text: '抱歉,系统出现错误,请稍后再试。', sender: 'ai' });
  39. this.isLoading = false;
  40. });
  41. }
  42. // 定义 sendMessageFromAI 方法
  43. sendMessageFromAI(message: string) {
  44. this.messages.push({ text: message, sender: 'ai' });
  45. }
  46. }