第35天~

这个得上一篇:https://ithelp.ithome.com.tw/articles/10258219

这里从product.service.ts档案:

https://ithelp.ithome.com.tw/upload/images/20210814/20119035aNNZI81SiV.png
新增语法:

page:{
   size:number,
   totalElements:number,
   totalPages:number,
   number:number
 }

复制这一段

getProductList(theCategoryId: number): Observable<Product[]> {

    const searchUrl = `${this.baseUrl}/search/findByCategoryId?id=${theCategoryId}`;

    return this.getProducts(searchUrl);
  }

修改程序码:

import { Product } from 'src/app/common/product';
import { ProductCategory } from './../common/product-category';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  private baseUrl = 'http://localhost:8080/api/products';

  private categoryUrl = 'http://localhost:8080/api/product-category';

  constructor(private httpClient: HttpClient) { }

  getProduct(theProductId: number) :Observable<Product>{

    const productUrl =`${this.baseUrl}/${theProductId}`;

    return this.httpClient.get<Product>(productUrl);

  }

  getProductListPaginate(thePage:number,
                         thePageSize:number,
                         theCategoryId: number): Observable<GetResponseProducts> {

    const searchUrl = `${this.baseUrl}/search/findByCategoryId?id=${theCategoryId}`
                    + `&page=${thePage}&size=${thePageSize}`;

    return this.httpClient.get<GetResponseProducts>(searchUrl);
  }


  getProductList(theCategoryId: number): Observable<Product[]> {

    const searchUrl = `${this.baseUrl}/search/findByCategoryId?id=${theCategoryId}`;

    return this.getProducts(searchUrl);
  }

  searchProducts(theKeyword: string): Observable<Product[]> {

    const searchUrl = `${this.baseUrl}/search/findByNameContaining?name=${theKeyword}`;

    return this.getProducts(searchUrl);

  }



  private getProducts(searchUrl: string): Observable<Product[]> {
    return this.httpClient.get<GetResponseProducts>(searchUrl).pipe(
      map(response => response._embedded.products)

    );
  }

  getProductCategories(): Observable<ProductCategory[]> {


    return this.httpClient.get<GetResponseProductCategory>(this.categoryUrl).pipe(
      map(response => response._embedded.productCategory)
      );
  }
}

interface GetResponseProducts {
  _embedded: {
    products: Product[];
 },
 page:{
   size:number,
   totalElements:number,
   totalPages:number,
   number:number
 }

}

interface GetResponseProductCategory {
  _embedded: {
    productCategory: ProductCategory[];
 }
}

再来到product-list.component.ts档案新增:

先变更
https://ithelp.ithome.com.tw/upload/images/20210814/20119035r0G2AiSfJ1.png

这里有一个地方要用工具新增:
https://ithelp.ithome.com.tw/upload/images/20210814/20119035INrc6D6f3m.png

剪下语法 previousCategoryId: number;

页数要从第1页开始所以要-1

接着再陆续新增到:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/common/product';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-list',

  templateUrl: './product-list-grid.component.html',

  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {

  products: Product[];
  currentCategoryId: number = 1;
  previousCategoryId: number=1;
  searchMode: boolean = false;

  thePageNumber: number = 1;
  thePageSize: number = 10;
  theTotalElements: number = 0;




  constructor(private productService: ProductService,
    private Route: ActivatedRoute) { }

  // tslint:disable-next-line: typedef
  ngOnInit() {
    this.Route.paramMap.subscribe(() => {
      this.listProducts();
    });
  }

  // tslint:disable-next-line: typedef
  listProducts() {

    this.searchMode = this.Route.snapshot.paramMap.has('keyword');

    if (this.searchMode) {
      this.handleSearchProducts();
    }
    else {
      this.handleListProducts();
    }


  }

  handleSearchProducts() {

    const theKeyword: string = this.Route.snapshot.paramMap.get('keyword');

    this.productService.searchProducts(theKeyword).subscribe(

      data => {
        this.products = data;

      }

    );


  }



  handleListProducts() {
    const hasCategoryId: boolean = this.Route.snapshot.paramMap.has('id');

    if (hasCategoryId) {
      this.currentCategoryId = +this.Route.snapshot.paramMap.get('id');
    }
    else {
      this.currentCategoryId = 1;
    }

    if (this.previousCategoryId != this.currentCategoryId) {
      this.thePageNumber = 1;

    }

    this.previousCategoryId=this.currentCategoryId;

    console.log(`currentCategoryId=${this.currentCategoryId},thePageNumber=${this.thePageNumber}`);


    this.productService.getProductListPaginate(this.thePageNumber -1,
      this.thePageSize,
      this.currentCategoryId)
      .subscribe(this.processResult());

    }

processResult(){
  return data =>{
    this.products=data._embedded.products;
    this.thePageNumber=data.page.number +1;
    this.thePageSize =data.page.size;
    this.theTotalElements =data.page.totalElements;

  };



  }
}

接着到档案product-list-grid.component.html更改加入CSS语法:

<div class="main-content">
  <div class="section-content section-content-p30">
    <div class="container-fluid">
      <div class="row">

        <!--内容区的显示-->
        <div *ngFor="let tempProduct of products" class="col-md-3">

          <div class="product-box">

            <a routerLink="/products/{{ tempProduct.id }}">


              <img src="{{ tempProduct.imageUrl }}" class="img-responsive">
            </a>

            <a routerLink="/products/{{ tempProduct.id }}">

              <h1>{{ tempProduct.name}}</h1>

            </a>
            <div class="price">{{ tempProduct.unitPrice | currency:'USD'}}</div>
            <a href="#" class="primary-btn">Add to cart</a>

          </div>
        </div>

        <div *ngIf="products?.length ==0" class="alert alert-warning col-md-12" role="alert">
          找不到这个品项

        </div>


      </div>
      <!--begin footer-->>
      <div class="footer-pagination">
        <div class="row">
          <div class="col-md-6"></div>

          <div class="col-md-6">
            <div class="row">

              <div class="col-md-9" style="padding-left: 30%">

                <ngb-pagination [(page)]="thePageNumber"
                                 [(pageSize)]="thePageSize"
                                 [(collectionSize)]="theTotalElements"
                                 (pageChange)="listProducts()">



                </ngb-pagination>




              </div>

            </div>

          </div>

        </div>

      </div>

    </div>
  </div>
</div>


https://ithelp.ithome.com.tw/upload/images/20210817/20119035pPqw3Vcp2j.png

这个的下一篇:https://ithelp.ithome.com.tw/articles/10258274


<<:  Ruby基本介绍(八)Rspec幼稚园等级实作

>>:  Day 50 (Node.js)

【Day 14】Google Apps Script - API 篇 - Document Service - 文件服务介绍

Docs(文件) Service API 可以让你完整的控制 Google Docs(文件)里的内...

大人也舍不得离开的公园 — 共融游乐场 Inclusive Playground

生活中有大大小小的设计,也许就在你我的日常中却未曾发现,其中一项替城市街景增添设计风采的设施就是公园...

Day-05 JavaScript阵列

阵列可以一次宣告大量的变数,有节省时间、空间的优点。在JavaScript里,阵列可储存不同型态的值...

Day13-TypeScript(TS)修改成员

今天要来讲解如何在 TypeScript (TS) 修改成员, 以我们之前的类别为例, let em...

[Re:PixiJS - Day45] 不同时期的学习 PixiJS 的过程与真完赛心得

来到这系列的最後一篇,除了心得结语外,也讨论的学习 PixiJS 的过程 时期1:不考虑效能,这时期...