When working on SpringBoot and angular connectivity I was passing data like getbooks by getmapping through JSON and it is getting printed on the server of Spring but after passing these values to angular using service angular is not printing the data on the server.
#SpringBoot Controller File -
@RestController
public class BookController {
@Autowired
BookService bookservice;
@GetMapping("/")
public String homePage() {
return "This is home Page";
}
@GetMapping("/addBook")
public String addBook(int id, String name, String author) {
bookservice.addBook(Book.builder().id(id).name(name).author(author).build());
return "Book Added";
}
@GetMapping("/deleteBook")
public String deleteBook(int id) {
bookservice.deleteBook(id);
return "Book deleted";
}
@GetMapping("/getBooks")
public String getAll() {
Gson gson = new Gson();
String json = gson.toJson(bookservice.getAll());
return json;
}
}
#SpringBoot service file -
@Service
public class BookService {
@Autowired
BookRepo repo;
public void addBook(Book book) {
repo.save(book);
repo.flush();
}
public List<Book> getAll(){
return repo.findAll();
}
public void deleteBook(int id) {
repo.delete(Book.builder().id(id).build());
}
}
#Angular service.ts-
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BookService {
constructor(private http : HttpClient) { }
getAll(){
return this.http.get<any>("http://localhost:8080/getBooks");
}
addBook(user:any){
return this.http.get("http://localhost:8080/addBook?id="+ user.id + "&name=" +user.name + "&author="+user.author);
}
deleteBook(id:any){
return this.http.get("http://localhost:8080/deleteBook?id="+id);
}
}
#appComponent.ts -
books:any;
constructor(private service:BookService) {}
ngOnInit():void{
this.loadData();
}
loadData():void {
this.service.getAll().subscribe(response => {
this.books = response;
console.log(this.books);
})
}
#appComponent.html -
<p *ngFor="let temp in books">
{{temp.name}} -- {{temp.author}}
</p>