从列表角度打开详细信息页面


`
//this is the list 
export class ListComponent implements OnInit {
books: Book[];
constructor(private service:HalkaApiService){ }
ngOnInit() {
this.service.getBooks().subscribe((data)=>{
this.books=data;
});
}
//this is the service
getBooks():Observable<Book[]>{
return this.http.get<Book[]>(this.path + "/Books");
}
getBook(id:number|string){
return this.http.get<Book[]>(this.path + `/Books ${id}`);
}
`

当我点击";细节";列表中的链接Html文件

首先,在booklist component.html中显示图书,如下所示:

<div *ngIf="books.length>0">
<ul *ngFor="let book of books">
<li> {{book.details}} - <a routerLink = "book-detail"/{{book.id}}">{{book.name}}</>
</li>
</ul>

然后创建另一个名为book detail的组件,进行路由{path:'book-detail/:id',component:BookDetailComponent},位于路由模块中。

然后在BookDetail组件中,执行以下操作:

export class BookDetailComponent implements OnInit {
book:Book;
constructor(private service:HalkaApiService, private activatedRoute:ActivatedRoute){ }
ngOnInit() {
this.activatedRoute.paramMap.pipe(
switchMap((params: ParamMap) => this.service.getBook(params.get('productId'))
)
).subscribe(result => { this.book = result; }, error => console.error(error));
}

然后在book-detail.component.html中执行此操作以显示图书详细信息:

<div *ngIf="book">
<p> {{book.title}}</p>
<p> written by {{book.author}}, released {{book.releaseYear}}</p>
<p> {{book.summary}}
</div>

仅此而已。我希望你能理解。感谢

最新更新