123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- // src/app/tab2/tab2.page.ts
- import { Component, OnInit } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- @Component({
- selector: 'app-tab2',
- templateUrl: './tab2.page.html',
- styleUrls: ['./tab2.page.scss'],
- })
- export class Tab2Page implements OnInit {
- messages: any[] = [];
- userInput: string = '';
- isLoading: boolean = false;
- constructor(private http: HttpClient) {}
- ngOnInit() {
- // 页面加载时自动发送一条随机的欢迎消息
- const welcomeMessages = [
- '我是您的AI医生小爱,有什么可以帮到您的吗?',
- '今天天气不错,可以出去散步哦。',
- '您好!我是您的健康助手,有什么我可以帮助您的吗?',
- '很高兴见到您!请告诉我您需要什么帮助。',
- '欢迎您!请问有什么健康方面的问题需要咨询吗?'
- ];
- const randomMessage = welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];
- this.sendMessageFromAI(randomMessage);
- }
- sendMessage() {
- if (this.userInput.trim() === '') return;
- this.messages.push({ text: this.userInput, sender: 'user' });
- this.isLoading = true;
- this.userInput = '';
- // 发送请求到 AI 服务
- this.http.post('https://your-ai-service-endpoint.com/api/chat', { message: this.userInput })
- .subscribe((response: any) => {
- this.messages.push({ text: response.message, sender: 'ai' });
- this.isLoading = false;
- }, (error) => {
- console.error('Error:', error);
- this.messages.push({ text: '抱歉,系统出现错误,请稍后再试。', sender: 'ai' });
- this.isLoading = false;
- });
- }
- // 定义 sendMessageFromAI 方法
- sendMessageFromAI(message: string) {
- this.messages.push({ text: message, sender: 'ai' });
- }
- }
|