Angular实现从书籍列表点击跳转至书籍详情组件
实现Angular列表跳转到书籍详情组件的方案
1. 配置路由规则
在项目的路由配置文件(通常是app-routing.module.ts)中,添加详情组件的路由,指定带id参数的路径:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ListComponent } from './list/list.component'; import { BookDetailComponent } from './book-detail/book-detail.component'; const routes: Routes = [ { path: 'books', component: ListComponent }, { path: 'books/:id', component: BookDetailComponent }, // 带id参数的详情路由 { path: '', redirectTo: '/books', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
2. 列表模板添加跳转链接
在list.component.html中,遍历书籍列表时,给每一项添加“详情”跳转链接,使用Angular的routerLink指令绑定带id的路由:
<ul> <li *ngFor="let book of books"> {{ book.title }} <a [routerLink]="['/books', book.id]">详情</a> </li> </ul>
3. 修复API服务的getBook方法
原服务代码里的请求URL有语法错误(空格问题),且返回类型应为单个Book而非数组,修正如下:
// 修改后的getBook方法 getBook(id: number|string): Observable<Book> { // 去掉URL里的空格,用正确的路径拼接 return this.http.get<Book>(`${this.path}/Books/${id}`); }
4. 详情组件加载数据
在BookDetailComponent中,通过ActivatedRoute获取路由参数,再调用API服务获取单本书籍数据:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HalkaApiService } from '../halka-api.service'; import { Book } from '../book.model'; @Component({ selector: 'app-book-detail', templateUrl: './book-detail.component.html', styleUrls: ['./book-detail.component.css'] }) export class BookDetailComponent implements OnInit { book: Book; constructor( private route: ActivatedRoute, private service: HalkaApiService ) { } ngOnInit(): void { // 获取路由中的id参数 const bookId = this.route.snapshot.paramMap.get('id'); if (bookId) { this.service.getBook(bookId).subscribe(data => { this.book = data; }); } } }
内容的提问来源于stack exchange,提问作者c3yo
相关产品推荐
相关产品推荐

