HarmonyOS_ArkTs_API(2)
社区互动系统是"梦想生活规划师"应用的核心社交组件,为用户提供一个分享梦想、进展和成就的平台。该系统基于鸿蒙HarmonyOS ArkTS构建,旨在培养一个支持性的社区环境,用户可以相互激励、交流经验并获得实现目标的动力。通过社区互动,用户不仅能记录个人成长历程,还能从他人的经验中获取灵感和见解。
·
HarmonyOS_ArkTs_API(2)
概述
是应用的核心社交组件,为用户提供一个分享梦想、进展和成就的平台。该系统基于鸿蒙HarmonyOS ArkTS构建,旨在培养一个支持性的社区环境,用户可以相互激励、交流经验并获得实现目标的动力。通过社区互动,用户不仅能记录个人成长历程,还能从他人的经验中获取灵感和见解。
数据模型
社区互动系统基于以下核心数据模型:
// 帖子实体
export interface Post {
id: number;
userId: number;
dreamId?: number;
title: string;
content: string;
images?: string;
likeCount: number;
commentCount: number;
viewCount: number;
createdAt: string;
updatedAt: string;
user?: User;
dream?: Dream;
isLiked?: boolean;
}
// 评论实体
export interface Comment {
id: number;
postId: number;
userId: number;
content: string;
likeCount: number;
createdAt: string;
updatedAt: string;
user?: User;
isLiked?: boolean;
}
核心功能
帖子管理
允许用户创建、查看、更新和删除社区帖子:
// 创建新帖子
export function createPost(post: Post): Promise<Post> {
try {
const requestData = {
title: post.title,
content: post.content,
images: post.images,
likeCount: 0,
commentCount: 0,
viewCount: 0
};
// 添加用户关联
if (post.userId) {
requestData.user = { id: post.userId };
}
// 添加梦想关联(可选)
if (post.dreamId) {
requestData.dream = { id: post.dreamId };
}
console.info(`创建帖子请求数据: ${JSON.stringify(requestData)}`);
return request<Post>(RequestMethod.POST, '/posts', requestData);
} catch (error) {
console.error(`创建帖子失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`创建帖子失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
// 获取帖子列表
export function getPosts(page: number = 0, size: number = 10): Promise<PageResponse<Post>> {
try {
return request<PageResponse<Post>>(
RequestMethod.GET,
'/posts',
{ page, size } as QueryParams
);
} catch (error) {
console.error(`获取帖子列表失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`获取帖子列表失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
评论系统
支持用户对帖子发表评论并参与讨论:
// 获取帖子评论
export function getCommentsByPostId(postId: number): Promise<Comment[]> {
try {
return request<Comment[]>(RequestMethod.GET, `/comments/post/${postId}`);
} catch (error) {
console.error(`获取帖子评论失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`获取帖子评论失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
// 添加评论
export function addComment(comment: Comment): Promise<Comment> {
try {
return request<Comment>(RequestMethod.POST, '/comments', comment);
} catch (error) {
console.error(`添加评论失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`添加评论失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
点赞功能
允许用户通过点赞表达对帖子和评论的支持:
// 点赞帖子
export function likePost(postId: number, userId: number): Promise<void> {
try {
return request<void>(RequestMethod.POST, `/posts/${postId}/like/${userId}`);
} catch (error) {
console.error(`点赞帖子失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`点赞帖子失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
// 取消点赞帖子
export function unlikePost(postId: number, userId: number): Promise<void> {
try {
return request<void>(RequestMethod.DELETE, `/posts/${postId}/like/${userId}`);
} catch (error) {
console.error(`取消点赞失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`取消点赞失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
UI 组件实现
社区互动系统包含以下核心UI组件:
帖子列表组件
@Component
export struct PostListComponent {
@State posts: Post[] = [];
@State loading: boolean = false;
@State currentPage: number = 0;
@State hasMore: boolean = true;
private refreshController: CustomRefreshController = new CustomRefreshController();
aboutToAppear() {
this.loadPosts();
}
loadPosts() {
this.loading = true;
getPosts(this.currentPage)
.then((response: PageResponse<Post>) => {
if (this.currentPage === 0) {
this.posts = response.content;
} else {
this.posts = [...this.posts, ...response.content];
}
this.hasMore = !response.last;
this.loading = false;
})
.catch((error: Error) => {
this.loading = false;
console.error(`加载帖子失败: ${error.message}`);
promptAction.showToast({ message: '加载帖子失败,请稍后重试' });
});
}
build() {
Column() {
List() {
ForEach(this.posts, (post: Post) => {
ListItem() {
PostItem({ post: post })
}
})
if (this.loading) {
ListItem() {
LoadingRow()
}
}
}
.onReachEnd(() => {
if (this.hasMore && !this.loading) {
this.currentPage++;
this.loadPosts();
}
})
}
.width('100%')
.height('100%')
}
}
帖子创建表单
@Component
export struct PostCreateForm {
@State post: Post = {
id: 0,
userId: 0,
title: '',
content: '',
images: '',
likeCount: 0,
commentCount: 0,
viewCount: 0,
createdAt: '',
updatedAt: ''
};
@State uploadedImages: string[] = [];
@State isSubmitting: boolean = false;
private router: Router = useRouter();
build() {
Column() {
// 帖子标题输入
TextInput({ placeholder: '请输入标题...' })
.height(56)
.fontSize(20)
.fontWeight(FontWeight.Medium)
.placeholderColor('#CCCCCC')
.backgroundColor(Color.White)
.onChange((value: string) => {
this.post.title = value;
})
// 帖子内容输入
TextArea({ placeholder: '分享你的梦想进展...' })
.height(200)
.fontSize(16)
.placeholderColor('#CCCCCC')
.backgroundColor(Color.White)
.onChange((value: string) => {
this.post.content = value;
})
// 图片上传区域
ImageUploaderComponent({
onImagesSelected: (urls: string[]) => {
this.uploadedImages = urls;
this.post.images = urls.join(',');
}
})
// 提交按钮
Button('发布')
.width('90%')
.height(48)
.backgroundColor('#4E6EF2')
.fontColor(Color.White)
.fontSize(16)
.fontWeight(FontWeight.Medium)
.margin({ top: 24 })
.onClick(() => {
this.submitPost();
})
.enabled(!this.isSubmitting)
}
.width('100%')
.padding(16)
.backgroundColor('#F8F8F8')
}
submitPost() {
// 表单验证
if (!this.post.title.trim()) {
promptAction.showToast({ message: '请输入标题' });
return;
}
if (!this.post.content.trim()) {
promptAction.showToast({ message: '请输入内容' });
return;
}
this.isSubmitting = true;
createPost(this.post)
.then(() => {
this.isSubmitting = false;
promptAction.showToast({ message: '发布成功' });
this.router.back();
})
.catch((error: Error) => {
this.isSubmitting = false;
console.error(`发布帖子失败: ${error.message}`);
promptAction.showToast({ message: '发布失败,请稍后重试' });
});
}
}
高级功能
梦想关联展示
帖子可以关联到特定梦想,使用户能够分享梦想进展:
@Component
struct DreamLinkPreview {
@Prop dream: Dream;
build() {
Row() {
Column() {
Text(this.dream.title)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Text(`目标日期: ${formatDate(this.dream.targetDate)}`)
.fontSize(14)
.fontColor('#666666')
.margin({ top: 4 })
ProgressBar({
value: this.dream.progress,
total: 100,
type: ProgressType.Linear
})
.width('100%')
.height(4)
.color('#4E6EF2')
.margin({ top: 8 })
Text(`进度: ${this.dream.progress}%`)
.fontSize(12)
.fontColor('#666666')
.margin({ top: 4 })
}
.padding(16)
.borderRadius(8)
.backgroundColor('#F5F7FF')
.layoutWeight(1)
}
.width('100%')
.onClick(() => {
router.pushUrl({
url: 'pages/dream/DreamDetailPage',
params: { dreamId: this.dream.id }
});
})
}
}
社区活跃度统计
系统跟踪并显示用户参与社区的活跃度指标:
export function getUserActivityStats(userId: number): Promise<UserActivityStats> {
try {
return request<UserActivityStats>(RequestMethod.GET, `/stats/activity/${userId}`);
} catch (error) {
console.error(`获取用户活跃度失败: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(`获取用户活跃度失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
@Component
struct ActivityStatsCard {
@State stats: UserActivityStats = null;
@State loading: boolean = true;
private userId: number;
aboutToAppear() {
this.loadStats();
}
loadStats() {
getUserActivityStats(this.userId)
.then((stats: UserActivityStats) => {
this.stats = stats;
this.loading = false;
})
.catch((err: Error) => {
console.error(`加载活跃度统计失败: ${err.message}`);
this.loading = false;
});
}
build() {
Column() {
Text('社区活跃度')
.fontSize(18)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 8 })
if (this.loading) {
LoadingProgress()
} else if (this.stats) {
Row() {
StatItem({ icon: $r('app.media.ic_posts'), value: this.stats.postsCount, label: '发布' })
StatItem({ icon: $r('app.media.ic_comments'), value: this.stats.commentsCount, label: '评论' })
StatItem({ icon: $r('app.media.ic_likes'), value: this.stats.likesGiven, label: '点赞' })
StatItem({ icon: $r('app.media.ic_received'), value: this.stats.likesReceived, label: '获赞' })
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
}
.width('100%')
.padding(16)
.backgroundColor(Color.White)
.borderRadius(12)
}
}
社区互动系统通过提供一个分享、交流和互动的空间,增强了用户体验,使梦想不仅是个人追求,也成为集体成长和互助的源泉。它促进了用户之间的联系,增强了应用的社交性和粘性,同时为用户提供了额外的动力和支持来坚持实现自己的梦想目标。
更多推荐
所有评论(0)