在处理SpringBoot和Angular 连接时,我通过JSON通过getmapping传递getbooks之类的数据,它将在Spring的服务器上打印,但在使用服务将这些值传递给Angular 后,Angular 不会在服务器上打印数据。
SpringBoot控制器文件-
@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 -
书籍:任何;
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>
2条答案
按热度按时间mzsu5hc01#
这里我们应该使用
*ngFor="let temp of books"
而不是*ngFor="let temp in books"
。请使用下面的代码片段:如果我们在
this.books
属性中正确获取数据,这可能会解决您的问题。希望这能有所帮助。1l5u6lss2#