angular - 删除选项在邮递员中按预期工作,从 Angular 应用程序触发时无法正常工作
问题描述
我创建了一个 spring boot crud 应用程序,对于资源我创建了对象的静态列表。
我能够通过邮递员按预期工作来执行所有的crud操作。通过角度时,我只能删除该静态列表中存在的对象。
我无法删除通过 angular 新创建的对象。
当我检查应用程序日志时,我可以看到端点的一些差异(找到//斜线)实际(用于静态列表的对象删除)-DELETE“/users/Sa/todos/4 ”差异(不适用于由创建的新对象me)- DELETE "/users//todos/5" 并且请求甚至没有输入控制器 Angular 代码:
todo-data.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Todo } from '../../Model/Todo';
@Injectable({
providedIn: 'root'
})
export class TodoDataService {
constructor(private http:HttpClient) { }
retrieveAllTodos(name:string){
return this.http.get<Todo[]>(`http://localhost:8080/users/${name}/todos`);
}
deleteTodoById(id:number,name:string){
return this.http.delete(`http://localhost:8080/users/${name}/todos/${id}`);
}
retrieveTodo(id:number,name:string){
return this.http.get<Todo>(`http://localhost:8080/users/${name}/todos/${id}`);
}
updateTodo(id:number,name:string,todo:Todo){
return this.http.put(`http://localhost:8080/users/${name}/todos/${id}`,todo);
}
createTodo(name:string,todo:Todo){
return this.http.post(`http://localhost:8080/users/${name}/todos`,todo);
}
}
列表待办事项.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Todo } from '../Model/Todo';
import { TodoDataService } from '../service/data/todo-data.service';
@Component({
selector: 'app-list-todos',
templateUrl: './list-todos.component.html',
styleUrls: ['./list-todos.component.css']
})
export class ListTodosComponent implements OnInit {
todos: Todo[];
deleteMessage:string;
constructor(private todoService: TodoDataService,private router:Router) { }
ngOnInit(): void {
this.refreshTodos();
console.log('inside list todos-ngoninit');
}
refreshTodos(){
this.todoService.retrieveAllTodos('Sathish').subscribe(
response => {
this.todos = response;
console.log(response);
},
error => {
console.log(error);
}
);
}
deleteTodo(id:number,name:string){
console.log(`todo Id ${id}`);
this.todoService.deleteTodoById(id,name).subscribe(
response=>{
this.deleteMessage=`Todo ${id} is deleted Successfully`;
this.refreshTodos();
}
);
}
updateTodo(id:number,name:string){
this.router.navigate(['todos',id,name]);
}
createTodo(){
this.router.navigate(['todos',-1,'Sathish']);
}
}
todo-component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Todo } from '../Model/Todo';
import { TodoDataService } from '../service/data/todo-data.service';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
id: number;
name: string;
todo: Todo = {
id: 0,
name: '',
description: '',
targetDate: new Date(),
done: false
};
constructor(private route: ActivatedRoute, private todoService: TodoDataService, private router: Router) { }
ngOnInit(): void {
this.route.paramMap.subscribe((params: ParamMap) => {
this.id = +params.get('id');
this.name = params.get('name');
});
if (this.id != -1) {
this.todoService.retrieveTodo(this.id, this.name).subscribe(
response => {
this.todo = response;
}
)
}
}
saveTodo() {
if (this.id === -1) {
this.todoService.createTodo(this.name,this.todo).subscribe(
response => {
console.log(response);
this.router.navigate(['todos']);
}
);
}
else {
this.todoService.updateTodo(this.id, this.name, this.todo).subscribe(
response => {
console.log(response);
this.router.navigate(['todos']);
}
);
}
}
}
春季启动代码:
控制器:
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class TodoResource {
@Autowired
private TodoHardCodedService todoHardCodedService;
@GetMapping("/users/{username}/todos")
public List<Todo> retrieveAllTodos(@PathVariable String username) {
return todoHardCodedService.getAllTodos();
}
@GetMapping("/users/{username}/todos/{id}")
public Todo retrieveTodo(@PathVariable String username,@PathVariable long id) {
return todoHardCodedService.findById(id);
}
@DeleteMapping("/users/{username}/todos/{id}")
public ResponseEntity<Void> deletetodo(@PathVariable String username, @PathVariable long id) {
System.out.println("Entered delete controller");
Todo todo = todoHardCodedService.deleteById(id);
if (todo != null)
return ResponseEntity.noContent().build();
return ResponseEntity.notFound().build();
}
@PutMapping("/users/{username}/todos/{id}")
public ResponseEntity<Todo> updateTodo(@PathVariable String username, @PathVariable long id,@RequestBody Todo todo){
Todo updatedTodo=todoHardCodedService.save(todo);
return new ResponseEntity<Todo>(updatedTodo,HttpStatus.OK);
}
@PostMapping("/users/{username}/todos")
public ResponseEntity<Void> createTodo(@PathVariable String username,@RequestBody Todo todo){
Todo createdTodo=todoHardCodedService.save(todo);
URI uri=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdTodo.getId()).toUri();
return ResponseEntity.created(uri).build();
}
}
服务:
@Service
public class TodoHardCodedService {
private static List<Todo> todos=new ArrayList<>();
private static long counter=0;
static {
todos.add(new Todo(++counter,"Sathish","Learn Frontend",new Date(),true));
todos.add(new Todo(++counter,"Sathi","Learn Fronte",new Date(),true));
todos.add(new Todo(++counter,"Sat","Learn Front",new Date(),true));
todos.add(new Todo(++counter,"Sa","Learn Fro",new Date(),false));
}
public List<Todo> getAllTodos(){
return todos;
}
public Todo findById(long id){
for (Todo todo:todos){
if (todo.getId()==id){
return todo;
}
}
return null;
}
public Todo deleteById(long id){
Todo todo=findById((id));
System.out.println("Inside delete by ID");
System.out.println(Arrays.toString(todos.toArray()));
System.out.println(todo);
if(todo!=null){
if(todos.remove(todo))
return todo;
}
return null;
}
public Todo save(Todo todo){
if (todo.getId()==-1 | todo.getId()==0){
todo.setId(++counter);
todos.add(todo);
}
else {
deleteById(todo.getId());
todos.add(todo);
}
return todo;
}
}
日志:
2020-10-02 00:57:17.744 DEBUG 22328 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : GET "/users/Sathish/todos", parameters={}
2020-10-02 00:57:17.744 DEBUG 22328 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.todo.app.TodoApplication.controller.TodoResource#retrieveAllTodos(String)
2020-10-02 00:57:17.752 DEBUG 22328 --- [nio-8080-exec-4] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
2020-10-02 00:57:17.752 DEBUG 22328 --- [nio-8080-exec-4] m.m.a.RequestResponseBodyMethodProcessor : Writing [[Todo(id=1, name=Sathish, description=Learn Frontend, targetDate=Fri Oct 02 00:49:40 IST 2020, isDon (truncated)...]
2020-10-02 00:57:17.752 DEBUG 22328 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2020-10-02 00:57:29.083 DEBUG 22328 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : DELETE "/users/Sa/todos/4", parameters={}
2020-10-02 00:57:29.083 DEBUG 22328 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.todo.app.TodoApplication.controller.TodoResource#deletetodo(String, long)
Entered delete controller
Inside delete by ID
[Todo(id=1, name=Sathish, description=Learn Frontend, targetDate=Fri Oct 02 00:49:40 IST 2020, isDone=true), Todo(id=2, name=Sathi, description=Learn Fronte, targetDate=Fri Oct 02 00:49:40 IST 2020, isDone=true), Todo(id=3, name=Sat, description=Learn Front, targetDate=Fri Oct 02 00:49:40 IST 2020, isDone=true), Todo(id=4, name=Sa, description=Learn Fro, targetDate=Fri Oct 02 00:49:40 IST 2020, isDone=false), Todo(id=5, name=, description=Learn Frontend also ride, targetDate=Fri Oct 02 00:57:13 IST 2020, isDone=false)]
Todo(id=4, name=Sa, description=Learn Fro, targetDate=Fri Oct 02 00:49:40 IST 2020, isDone=false)
2020-10-02 00:57:29.091 DEBUG 22328 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
2020-10-02 00:57:29.091 DEBUG 22328 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Nothing to write: null body
2020-10-02 00:57:29.091 DEBUG 22328 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 204 NO_CONTENT
2020-10-02 00:57:29.099 DEBUG 22328 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/users/Sathish/todos", parameters={}
2020-10-02 00:57:29.099 DEBUG 22328 --- [nio-8080-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.todo.app.TodoApplication.controller.TodoResource#retrieveAllTodos(String)
2020-10-02 00:57:29.099 DEBUG 22328 --- [nio-8080-exec-6] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
2020-10-02 00:57:29.099 DEBUG 22328 --- [nio-8080-exec-6] m.m.a.RequestResponseBodyMethodProcessor : Writing [[Todo(id=1, name=Sathish, description=Learn Frontend, targetDate=Fri Oct 02 00:49:40 IST 2020, isDon (truncated)...]
2020-10-02 00:57:29.099 DEBUG 22328 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2020-10-02 00:57:36.191 DEBUG 22328 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : DELETE "/users//todos/5", parameters={}
2020-10-02 00:57:36.191 DEBUG 22328 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-10-02 00:57:36.199 DEBUG 22328 --- [nio-8080-exec-7] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-10-02 00:57:36.199 DEBUG 22328 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-10-02 00:57:36.207 DEBUG 22328 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for DELETE "/error", parameters={}
2020-10-02 00:57:36.207 DEBUG 22328 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2020-10-02 00:57:36.215 DEBUG 22328 --- [nio-8080-exec-7] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
2020-10-02 00:57:36.215 DEBUG 22328 --- [nio-8080-exec-7] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Fri Oct 02 00:57:36 IST 2020, status=404, error=Not Found, message=No message available, (truncated)...]
2020-10-02 00:57:36.231 DEBUG 22328 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
解决方案
谢谢你的时间。
我在角度代码中犯了一个小的逻辑错误,在创建发布请求时,我设置了 id=-1 并且名称留空。
因为我使用名称字段来创建请求 url DELETE "/users/{username}/todos/4 它变成空白 /users//todos/4 并且无法匹配后端的 url。
得到那个错误。
我感到很高兴,当我们错了时,我们有人纠正我们
推荐阅读
- apache - 如何在子文件夹中部署带有 mod_rewrite 的 Nuxt SSR?
- unity3d - 从球自己的位置移动球Unity3D
- c# - 在 Azure 应用服务上托管 Web api 时出现无效异常
- aurelia - 双向绑定不适用于 Aurelia 自定义属性
- azure - 使用 Azure AD B2C 进行 DevOps?
- c# - 什么是 MapHeader?
- server - 如何使用 ngrok 公开两个端口?
- python - 如何使用 dask 将大量列数据写入 excel 文件的列?
- javascript - 如何在文本区域中插入具有 SVG 格式的自定义表情符号
- javascript - 从 ReactJs 中的异步代码中捕获异常的问题