1. book.json
假设我们手上有个json文件内容是
[
{
"id": 1,
"title": "Book One",
"author": "Author One",
"description": "Description of Book One"
},
{
"id": 2,
"title": "Book Two",
"author": "Author Two",
"description": "Description of Book Two"
}
]
创建一个 Book
实体类,定义书籍对象的结构。
// book.ets
export default class Book {
id: number;
title: string;
author: string;
description: string;
constructor(id: number, title: string, author: string, description: string) {
this.id = id;
this.title = title;
this.author = author;
this.description = description;
}
}
3. BookService
服务类
// book-service.ets
import Book from './book';
export default class BookService {
getBooks(): Book[] {
const jsonStr = this.readJSON();
const jsonArray = JSON.parse(jsonStr);
return jsonArray.map((item) => {
return new Book(item.id, item.title, item.author, item.description);
});
}
private readJSON(): string {
// 使用 @Resource 读取 book.json 文件
return AppStorage.get<string>('@app.book.json');
}
}
4. BookListComponent
书籍列表组件
// book-list.ets
import Book from './book';
import BookService from './book-service';
@Entry
@Component
struct BookListComponent {
@State books: Book[] = []
build() {
Column() {
ForEach(this.books, (book: Book) => {
Text(book.title).onClick(() => this.viewBookDetails(book))
})
}.onInit(this.fetchBooks)
}
fetchBooks() {
const bookService = new BookService();
this.books = bookService.getBooks();
}
viewBookDetails(book: Book) {
router.push({
uri: 'pages/book-detail',
params: {
book: book
}
});
}
}
5. BookDetailComponent
书籍详情组件
// book-detail.ets
import Book from './book';
@Entry
@Component
struct BookDetailComponent {
@State book: Book = new Book(0, '', '', '')
build() {
Column() {
Text(this.book.title).fontSize(24)
Text(this.book.author).fontSize(20)
Text(this.book.description).fontSize(16)
}.onInit(this.fetchBookDetails)
}
fetchBookDetails() {
const book = this.$route.params.book;
if (book) {
this.book = book;
}
}
}