iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

把前後分離製作的網站組起來系列 第 26

倒數第5天

這篇一樣要先來聊product-list.component.ts檔案
程式碼從-

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;

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

  // tslint:disable-next-line: typedef
  ngOnInit() {
    
    this.listProducts();
  }

  // tslint:disable-next-line: typedef
  listProducts() {
    this.productService.getProductList().subscribe(
      data => {
        this.products = data;
      }
    )
  }

}

繼續加入 route的部分-因為this.listProducts();這句話先打了
所以要把{往下移
程式碼改成-

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;

  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.productService.getProductList().subscribe(
      data => {
        this.products = data;
      }
    )
  }

}

再來加入確認id可以通過的語法:

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;

  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() {

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

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

    this.productService.getProductList().subscribe(
      data => {
        this.products = data;
      }
    )
  }

}


然後在this.productService.getProductList().subscribe裡面加入this.currentCategoryId

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;

  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() {

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

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

    this.productService.getProductList(this.currentCategoryId).subscribe(
      data => {
        this.products = data;
      }
    )
  }

}



再到product.service.ts新增theCategoryId: number
https://ithelp.ithome.com.tw/upload/images/20210724/20119035DWJhODFdvD.png

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

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

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

  constructor(private httpClient: HttpClient) { }

  getProductList(theCategoryId: number): Observable<Product[]> {
    return this.httpClient.get<GetResponse>(this.baseUrl).pipe(
      map(response => response._embedded.products)
    );
  }
}

interface GetResponse {
  _embedded: {
    products: Product[];
 };
}



回到SPRING BOOT 準備新增page findByCategoryId(@RequestParam("id") Long id, Pageable pageable);
https://ithelp.ithome.com.tw/upload/images/20210724/20119035ys4Yp2nIVc.png

package com.huang.ecommerce.dao;

import com.huang.ecommerce.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestParam;

import java.awt.print.Pageable;


@CrossOrigin("http://localhost:4200")
public interface ProductRepository extends JpaRepository<Product,Long> {

    page<Product> findByCategoryId(@RequestParam("id") Long id, Pageable pageable);
}

準備引入:
WINDOWS按CTRL+ALT+S出現-找到editor->general->auto import
https://ithelp.ithome.com.tw/upload/images/20210724/20119035oT8NQLk2lq.png

打V兩個..然後按OK
https://ithelp.ithome.com.tw/upload/images/20210724/20119035wjZYgstgWn.png
會加入:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

https://ithelp.ithome.com.tw/upload/images/20210724/20119035ubQfgWRgRE.png

然後重新啟動SPRING boot用網址http://localhost:8080/api/products/search/findByCategoryId?id=1 查看

有成功跳轉:
https://ithelp.ithome.com.tw/upload/images/20210724/20119035Uj6DTjHoHd.png


用網址http://localhost:8080/api/products/search/findByCategoryId?id=2 查看
https://ithelp.ithome.com.tw/upload/images/20210724/20119035zMPKMaDaU4.png


又回到VS CODE把原來的程式碼:

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

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

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

  constructor(private httpClient: HttpClient) { }

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

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





    return this.httpClient.get<GetResponse>(this.baseUrl).pipe(
      map(response => response._embedded.products)
    );
  }
}

interface GetResponse {
  _embedded: {
    products: Product[];
 };
}


增加和修改this.baseUrl變成searchUrl

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

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

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

  constructor(private httpClient: HttpClient) { }

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

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





    return this.httpClient.get<GetResponse>(searchUrl).pipe(
      map(response => response._embedded.products)
    );
  }
}

interface GetResponse {
  _embedded: {
    products: Product[];
 };
}


到網站看按書是書/按咖啡是咖啡
成功跳轉

http://localhost:4200/category/1

https://ithelp.ithome.com.tw/upload/images/20210724/20119035qzdSkFXctI.png

http://localhost:4200/category/2

https://ithelp.ithome.com.tw/upload/images/20210724/20119035AIUarTT8oY.png


再延續昨天的閒聊~也是補到這裡會刪掉喔~
就是使用絕對路徑~
來找到檔案內容的方法
/images/emoticon/emoticon25.gif

就是要打絕對路徑~如果像我一樣容易迷路的人 可以加入 System.out.println(System.getProperty("user.dir"));
這句找到絕對路徑在哪裡(我這裡txt檔因為已經跟JAVA檔放在一起..所以基本上會在同一個地方)
https://ithelp.ithome.com.tw/questions/10200429#answer-367633

DEAR ALL 我們明天見/images/emoticon/emoticon08.gif


上一篇
倒數第6天
下一篇
倒數第4天
系列文
把前後分離製作的網站組起來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言