有没有一种方法可以使用 api 搜索返回的项目列表中的 id 从 api 中提取一些数据?

Is there a way to extract some data from an api using id in a list of items returned in an api search?

我正在尝试 select 从使用 google 本书 api 搜索返回的图书列表中查找图书。当我 select 一本书时,我想通过路由参数获取 id 并在右侧显示 selected 书的更多详细信息。

我已经知道如何通过路由参数获取id,但是在我select之后显示书的详细信息是现在的问题。

我该怎么做?

本书-search.component.html

<div class="row">
  <div class="col-xs-12">
    <form (ngSubmit)="onSearch(f)" #f="ngForm">
      <div class="input-group-append">
        <input
          type="search"
          class="form-control"
          placeholder="Search for books"
          id="search"
          name="search"
          ngModel
        />
        <button class="btn btn-outline-primary" type="submit">Search</button>
      </div>
    </form>
  </div>
</div>
<br />
<div *ngIf="isLoading" style="padding-left: 70px;">
  <app-loading-spinner></app-loading-spinner>
</div>
<div class="row">
  <div *ngIf="books && !isLoading">
    <div class="col-xs-12">
      <div
        [routerLink]="['/books', book.id]"
        routerLinkActive="active"
        style="cursor: pointer;"
        *ngFor="let book of books"
      >
        <img
          src="{{ book.volumeInfo.imageLinks.thumbnail }}"
          alt="{{ book.volumeInfo.title }}"
          style="max-height: 50px;"
        />
        {{ book.volumeInfo.title }}
      </div>
    </div>
  </div>
  <div>
    <router-outlet></router-outlet>
  </div>
</div>

本书-search.component.ts

import { Component, OnInit } from "@angular/core";
import { BookSearchService } from "./book-search.service";
import { NgForm } from "@angular/forms";

@Component({
  selector: "app-book-search",
  templateUrl: "./book-search.component.html",
  styleUrls: ["./book-search.component.css"]
})
export class BookSearchComponent implements OnInit {
  books: [];
  isLoading = false;

  constructor(private bookSearchService: BookSearchService) {}

  ngOnInit() {}

  onSearch(form: NgForm) {
    this.isLoading = true;
    const value = form.value.search;
    this.bookSearchService.searchBooks(value).subscribe(resData => {
      this.books = resData.items;
      console.log(resData);
      this.isLoading = false;
    });
  }
}

图书搜索-detail.component.ts

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";

@Component({
  selector: "app-book-search-detail",
  templateUrl: "./book-search-detail.component.html",
  styleUrls: ["./book-search-detail.component.css"]
})
export class BookSearchDetailComponent implements OnInit {
  id: any;
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.id = params["id"];
      console.log(this.id);
    });
  }
}

由于将book-id传递给了detail-component,所以在ngOnInit方法中可以根据id获取对应的实体详情。

因此,您避免(也不需要)传入实际实体本身。