当前位置: 首页 > news >正文

「Mac畅玩AIGC与多模态41」开发篇36 - 用 ArkTS 构建聚合搜索前端页面

一、概述

本篇基于上一节 Python 实现的双通道搜索服务(聚合 SearxNG + 本地知识库),构建一个完整的 HarmonyOS ArkTS 前端页面。用户可在输入框中输入关键词,实时查询本地服务 http://localhost:5001/search?q=...,返回结果自动渲染在页面中,支持中文和英文关键词的综合查询体验。

二、目标说明

  • 使用 ArkTS 开发搜索界面组件
  • 输入关键词并发起 HTTP 请求
  • 支持异步加载并实时显示搜索结果
  • 解析标准结构体 { results: [{ title, content, url }] } 并渲染结果列表

三、目录结构

SearchApp/
├── src/main/ets/
│   ├── pages/
│   │   └── Index.ets                # 主页面:包含输入框、按钮和结果列表
│   ├── components/
│   │   └── SearchDisplay.ets        # 每条搜索结果的显示组件
│   ├── services/
│   │   └── SearchService.ets        # 封装 HTTP 调用和 JSON 解析
│   ├── utils/
│   │   └── HttpClient.ets           # 通用的 httpRequestText 实现
│   ├── types/
│   │   └── SearchTypes.ets          # SearchResponse 和 SearchResultList 类型定义
│   └── configs/
│       └── Config.ets               # 搜索 API URL 配置项

四、关键代码实现

1. 配置文件(Config.ets)

export const config = {searchApiUrl: "http://192.168.1.103:5001/search"
}

2. 类型定义(SearchTypes.ets)

// src/main/ets/types/SearchTypes.ets/*** 单条搜索结果*/
export interface SearchResponse {title: stringcontent: stringurl: string
}/*** 后端返回的结果结构*/
export interface SearchResultList {results: SearchResponse[]
}

3. 搜索服务(SearchService.ets)

// src/main/ets/services/SearchService.etsimport { httpRequestText } from '../utils/HttpClient'
import { http } from '@kit.NetworkKit'
import { SearchResponse, SearchResultList } from '../types/SearchTypes'export class SearchService {private apiUrl: stringconstructor(apiUrl: string) {this.apiUrl = apiUrl}public async search(query: string,onItem?: (item: SearchResponse) => void): Promise<SearchResponse[]> {const url: string = `${this.apiUrl}?q=${encodeURIComponent(query)}`let buffer: string = ''try {await httpRequestText(url,http.RequestMethod.GET,'',60000,(chunk: string) => {buffer += chunk})} catch {console.error('SearchService 网络请求失败')throw new Error('Search 请求失败')}let list: SearchResponse[]try {// 使用已定义的接口类型,而非内联对象字面量const parsed = JSON.parse(buffer) as SearchResultListlist = parsed.results} catch {console.error('SearchService JSON 解析失败,buffer=', buffer)throw new Error('返回数据格式错误')}list.forEach((item: SearchResponse) => {if (onItem) {onItem(item)}})return list}
}

4. 单条结果展示组件(SearchDisplay.ets)

// src/main/ets/components/SearchDisplay.etsimport { SearchResponse } from '../types/SearchTypes';@Component
export struct SearchDisplay {private item!: SearchResponse;build() {Column() {Text(this.item.title).fontSize(18).fontWeight('bold').margin({ bottom: 4 });Text(this.item.content).fontSize(14).margin({ bottom: 4 });Text(this.item.url).fontSize(12).fontColor('#888');    // 使用 fontColor 设置文本颜色}.padding(10).backgroundColor('#F5F5F5').margin({ bottom: 10 });}
}

5. 主页面实现(Index.ets)

// src/main/ets/pages/Index.etsimport { SearchDisplay } from '../components/SearchDisplay'
import { config } from '../configs/Config'
import { SearchService } from '../services/SearchService'
import { SearchResponse } from '../types/SearchTypes'@Entry
@Component
export struct Index {@State query: string = 'HarmonyOS'@State results: SearchResponse[] = []public async fetchData(): Promise<void> {this.results = []try {const res: SearchResponse[] = await new SearchService(config.searchApiUrl).search(this.query)this.results = res} catch {console.error('搜索失败')}}public build(): void {Column() {TextInput({ text: this.query, placeholder: '输入搜索关键词,如 ChatGPT' }).onChange((value: string): void => {this.query = value}).width('match_parent').height(50).width(300).margin({ bottom: 12 })Button('搜索').width('match_parent').height(50).onClick((): void => {this.fetchData()}).margin({ bottom: 20 })ForEach(this.results, (item: SearchResponse): void => {SearchDisplay({ item })})}.padding({ left: 20, right: 20, top: 20 })}
}

五、运行效果示例

如图所示,输入 “HarmonyOS” 或 “ChatGPT” 后,前端立即展示聚合搜索结果:

在这里插入图片描述

在这里插入图片描述

六、总结

本篇在第40篇的 Python 搜索服务基础上,构建了 HarmonyOS 的前端页面。整个流程完整覆盖:

  • 构建 TextInput、按钮、结果展示组件
  • 使用 HttpClient.ets 封装请求
  • 实现 JSON 结构的严格类型解析与响应式渲染

通过该示例,开发人员可以快速将本地服务能力集成进 HarmonyOS App,用于搭建多模态查询工具、Dify Agent 插件原型或独立智能体前端。下一步可考虑引入分页、加载动画或语音输入等多模态交互能力。

http://www.xdnf.cn/news/495883.html

相关文章:

  • Java 方法向 Redis 里操作字符串有什么需要注意的?​
  • OpenWebUI新突破,MCPO框架解锁MCP工具新玩法
  • Java 多态学习笔记(详细版)
  • 一场关于BOM物料清单的深度对话
  • 阿里通义万相 Wan2.1-VACE:开启视频创作新境界
  • 重排序模型解读:gte-multilingual-reranker-base 首个GTE系列重排模型诞生
  • 【计算机视觉】论文精读《基于改进YOLOv3的火灾检测与识别》
  • 区块链可投会议CCF C--IPCCC 2025 截止6.7 附录用率
  • 2024 山东省ccpc省赛
  • 数据库——SQL约束窗口函数介绍
  • windows触摸板快捷指南
  • 一二维前缀和与差分
  • C++学习-入门到精通-【7】类的深入剖析
  • 【Redis】redis用作缓存和分布式锁
  • 湖北理元理律师事务所:科学债务管理模型构建实录
  • 无法加载文件 E:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本
  • 支持同步观看的媒体服务器GhostHub
  • 【Linux笔记】——线程互斥与互斥锁的封装
  • 使用 Python 连接 Oracle 23ai 数据库完整指南
  • 小黑独自咖啡厅享受思考心流:82. 删除排序链表中的重复元素 II
  • DAY28-类的定义和方法
  • 计算机视觉与深度学习 | LSTM应用于数据插值
  • 下集:一条打包到底的静态部署之路
  • JMeter 教程:编写 POST 请求脚本访问百度
  • SQL Server 与 Oracle 常用函数对照表
  • 二进制与十进制互转的方法
  • 使用Maven部署WebLogic应用
  • 信贷风控笔记6——风控常用指标(面试准备14)
  • MATLAB学习笔记(六):MATLAB数学建模
  • Uniapp、Flutter 和 React Native 全面对比