Mục Lục
- Giới thiệu
- RCP là gì?
- Tạo Mô Hình Dữ Liệu
- Tạo Hằng Số
- Thực Hiện Gọi API
- Tạo ViewModel và Lấy Sách
- Tạo Thành Phần Card cho Sách
- Hiển Thị Sách trên Trang Sách
- Kết Luận
- Câu Hỏi Thường Gặp
Giới thiệu
Chào mọi người 😊
Trong bài viết này, chúng ta sẽ tìm hiểu cách lấy dữ liệu từ Google Books API bằng RCP (Remote Communication Kit) trong dự án HarmonyOS Next.
RCP là gì?
RCP là một mô-đun cung cấp khả năng yêu cầu dữ liệu qua HTTP. Với khả năng này, ứng dụng của bạn có thể gửi yêu cầu dữ liệu sử dụng các phương thức HTTP như GET, POST, HEAD, PUT, DELETE, PATCH và OPTIONS.
Các Thực Hành Tốt Nhất
- Sử dụng các phương thức HTTP đúng cách: Lựa chọn phương thức phù hợp với loại yêu cầu bạn cần thực hiện.
- Xử lý lỗi: Luôn xử lý các lỗi có thể xảy ra trong quá trình gửi yêu cầu và nhận phản hồi.
- Tối ưu hóa luồng dữ liệu: Giảm thiểu số lượng và kích thước dữ liệu gửi đi và nhận về.
Các Cạm Bẫy Thường Gặp
- Không kiểm tra trạng thái phản hồi: Luôn kiểm tra mã trạng thái HTTP để đảm bảo yêu cầu thành công.
- Bỏ qua thời gian phản hồi: Theo dõi thời gian phản hồi để nhận biết các vấn đề về hiệu suất.
Mẹo Hiệu Suất
- Sử dụng bộ nhớ cache: Lưu trữ các phản hồi để giảm thiểu yêu cầu không cần thiết.
- Gửi yêu cầu bất đồng bộ: Tránh làm chậm giao diện người dùng trong khi chờ phản hồi.
Tạo Mô Hình Dữ Liệu
Chúng ta sẽ bắt đầu bằng việc tạo các mô hình dữ liệu cần thiết để xử lý dữ liệu từ API.
BookModel.ets
typescript
export default interface BookModel {
title: string;
pageCount: number;
image: string;
description: string;
categories: [];
}
ImagesModel.ets
typescript
export interface ImagesModel {
smallThumbnail: string;
}
RSPModel.ets
typescript
import { volModel } from './volModel';
export interface RSPModel {
items: volModel[];
}
volModel.ets
typescript
import { VolumeInfoModel } from './VolumeInfoModel';
export interface volModel {
volumeInfo: VolumeInfoModel;
}
VolumeInfoModel.ets
typescript
import { ImagesModel } from './ImagesModel';
export interface VolumeInfoModel {
title: string;
pageCount: number;
imageLinks: ImagesModel;
description: string;
categories: [];
}
Tạo Hằng Số
Chúng ta sẽ định nghĩa một số hằng số cần thiết để giao tiếp với API.
Constants.ets
typescript
export const BASE_URL = 'https://www.googleapis.com/books/v1/';
export const url =
'https://www.googleapis.com/books/v1/volumes?q=api&fields=items(volumeInfo/title,volumeInfo/pageCount,volumeInfo/imageLinks/smallThumbnail,volumeInfo/description,volumeInfo/categories)';
Thực Hiện Gọi API
Chúng ta sẽ tạo một hàm để khởi tạo phiên làm việc với RCP và thực hiện yêu cầu.
RCP.ets
typescript
import { rcp } from '@kit.RemoteCommunicationKit';
import { BASE_URL } from './Constants';
function sessionConfig(): rcp.SessionConfiguration {
return {
baseAddress: BASE_URL
};
}
export function getHttp(url: string) {
const session = rcp.createSession(sessionConfig());
return session.get(`${url}`).then((res) => res.toJSON()).finally(() => {
session.close();
});
}
Tạo ViewModel và Lấy Sách
Bây giờ, chúng ta sẽ tạo ViewModel để lấy dữ liệu sách từ API.
BookViewModel.ets
typescript
import BookModel from '../model/BookModel';
import { RSPModel } from '../model/RSPModel';
import { volModel } from '../model/volModel';
import { getHttp } from '../utils/RCP';
import { url } from '../utils/Constants';
@Observed
export class BookViewModel {
private static _instance: BookViewModel;
allBooks: BookModel[] = [];
private constructor() {}
public static get instance(): BookViewModel {
if (!BookViewModel._instance) {
BookViewModel._instance = new BookViewModel();
}
return BookViewModel._instance;
}
async getBooks() {
const response = await getHttp(url) ?? [];
const rsp = response as RSPModel;
this.allBooks = rsp.items.map<BookModel>((i: volModel) => {
return {
title: i.volumeInfo.title,
pageCount: i.volumeInfo.pageCount,
image: i.volumeInfo.imageLinks.smallThumbnail,
description: i.volumeInfo.description,
categories: i.volumeInfo.categories
};
});
console.info('getBooks', JSON.stringify(this.allBooks, null, 3));
}
}
Tạo Thành Phần Card cho Sách
Chúng ta sẽ tạo một thành phần card để hiển thị thông tin sách.
BookCardComponent.ets
typescript
@Component
export struct BookCardComponent {
@Prop title: string;
@Prop pageCount: number;
@Prop image: string;
@Prop categories: Array<string>;
build() {
Column() {
Image(this.image).width(60).height(70).padding({ bottom: 3 });
Text(this.categories.join(', ')).fontSize(9).fontColor(Color.White).padding({ bottom: 3 });
Text(this.title).fontSize(11).fontColor(Color.White).padding({ bottom: 3 });
Text(this.pageCount.toString() + ' trang').fontSize(9).fontColor(Color.White);
}.padding(2).width('70%').borderRadius(20);
}
}
Hiển Thị Sách trên Trang Sách
Cuối cùng, chúng ta sẽ hiển thị sách trên trang sách.
BooksPage.ets
typescript
import { BookCardComponent } from '../component/BookCardComponent';
import { BookViewModel } from '../viewmodel/BookViewModel';
import BookModel from '../model/BookModel';
@Entry
@Component
struct HomePage {
scroller: Scroller = new Scroller();
@State viewModel: BookViewModel = BookViewModel.instance;
aboutToAppear() {
this.viewModel.getBooks();
}
build() {
Column() {
Text($r('app.string.books'));
Scroll(this.scroller) {
Column() {
ForEach(this.viewModel.allBooks, (book: BookModel, index: number) => {
BookCardComponent({
image: book.image,
title: book.title,
pageCount: book.pageCount,
categories: book.categories
}).padding({ bottom: 4 });
Divider().height(2).color(0xCCCCCC).padding({ left: 40, right: 40, bottom: 10 });
}, (item: string, index: number) => item);
}.padding({ bottom: 25 });
}.width('100%').height('100%');
}.backgroundColor(Color.Black).padding({ top: 10, bottom: 10 }).width('100%').height('100%');
}
}
Kết Luận
Trong bài viết này, chúng ta đã trình bày cách lấy dữ liệu từ Google Books API bằng cách sử dụng RCP của Huawei trong dự án HarmonyOS Next. Bằng cách tích hợp RCP với kiến trúc ViewModel sạch, chúng ta đã có thể cấu trúc các yêu cầu mạng của mình một cách hiệu quả và biến các phản hồi của API thành mô hình dữ liệu sử dụng được.
Câu Hỏi Thường Gặp
- RCP có hỗ trợ các phương thức HTTP nào?
RCP hỗ trợ các phương thức HTTP như GET, POST, PUT, DELETE, PATCH, và OPTIONS. - Làm thế nào để xử lý lỗi khi gọi API?
Bạn có thể sử dụng các cấu trúc điều kiện để kiểm tra mã trạng thái phản hồi và xử lý các lỗi tương ứng.