I’m facing difficulties when adding a new component to an existing Angular application that is connected to a Spring Boot backend. Here are the details of my issue:
I’m working on an application that uses Angular for the frontend and Spring Boot for the backend. I want to add a new component called ProductListComponent to my Angular frontend.
Problem:
After creating the ProductListComponent component using the ng generate component product-list command, I tried to include it in my application by using it in the app.component.html file. However, when I launch the application, I receive an error indicating that the app-product-list component is not recognized.
Here’s the content of my product-list.component.ts file:
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../product.service';
import { Product } from '../product';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit {
products: Product[] = [];
constructor(private productService: ProductService) { }
ngOnInit(): void {
this.getAllProducts();
}
getAllProducts(): void {
this.productService.getAllProducts()
.subscribe(products => this.products = products);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Product } from './product';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private baseUrl = 'http://localhost:8180';
constructor(private http: HttpClient) { }
getAllProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`${this.baseUrl}/products`);
}
getProductById(id: number): Observable<Product> {
return this.http.get<Product>(`${this.baseUrl}/product/${id}`);
}
}
spring boot
package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.account.Dao.ProductList;
import com.account.bean.Product;
@RestController
public class ProductController {
@Autowired
private ProductList productList; // Injectez votre classe DAO
@GetMapping("/products")
public List<Product> getAllProducts() {
return productList.getAllProducts();
}
@GetMapping("/product/{id}")
public Product getProductById(@PathVariable int id) {
return productList.getSingleProduct(id);
}
}
I checked that the ProductListComponent component was correctly generated by Angular and is present in the src/app/product-list folder.
user23298973 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.