如何在数组对象中只显示一条记录的角度问题



当我从像这样的数组中获得一条记录时,我遇到了一个问题

data.service.ts

getOneBookDetail(isbn:any) {
const headers = new HttpHeaders().set("Content-Type", "application/json");

// console.log("=============" + isbn )
console.log(headers)
return this.http.get('http://localhost:10888/bookdetail/?isbn='+ isbn).subscribe(
(val) => { // Get has no error and response has body
console.log("Get successful value returned in body", val);
},
response => {
console.log("Get call in error", response);
},
() => { // Get has no error, response has no body
console.log("The Get observable is now completed.");
});
}
home.component.ts
getBookDetail(book) {
this.data.getOneBookDetail(book.isbn)   //isbn of book
}

我可以点击的书名

<a routerLink="/bookdetail/{{book.isbn}}" (click)="getBookDetail(book)"><h3>{{ book.title }}</h3></a>

我可以得到一个我在控制台中看到的物体

Get successful value returned in body [{…}]

0: {_id: "5fc91e5aa700213eb8c52de0", title: "A Promised Land"

[{…}]是0:{_id:"5fc91e5aa700213eb8c52de0",标题:"应许之地";……

现在我想把这个对象放到一个页面上,调用bookdetail只显示这本书的详细信息,但现在仍然显示所有的书下面是书籍细节组件

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
selector: 'app-bookdetail',
templateUrl: './bookdetail.component.html',
styleUrls: ['./bookdetail.component.scss']
})
export class BookDetailComponent implements OnInit {

h1Style: boolean = false;
books: Object;

constructor(private data: DataService) {}

ngOnInit() {
this.data.getBooks().subscribe(data=> {
console.log({data})  //show data
this.books = data
//console.log(this.books);
})
}

}

在bookdetail html

<h1>Book-detail</h1>
<div *ngIf="books" class="bookdetail-block">
<div *ngFor="let bookdetail of books" class="bookdetail">
<h1>{{bookdetail.title}}</h1>
<p><img [src]="bookdetail.image" ></p>
<p>{{bookdetail.author}}</p>
<p>{{bookdetail.price}}</p>
<p>{{bookdetail.isbn}}</p>
<p>{{bookdetail.description}}</p>

</div>
</div>

我怎么能只显示我有选择?

我认为这个问题在书的细节ngOnInit((中??

Zico,通常的想法是您在您的"细节部件";,请参阅文档:您可以使用switchMap,在获得参数后,生成dataService.getOneBookDetail(id)。在订阅中,您等于对变量的响应,并且只显示变量

book:any
constructor(private activatedRoute:ActivatedRoute,private dataService:DataService){}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => {
const ibs=params.get('isbn');
return this.dataService.getOneBookDetail(ibs);
}).subscribe(res=>{
book=res;
})
);
}

另一个想法是在路线之间传递数据,如显示Netanel Basal

最新更新