使用PUT方法时console.log无法显示编辑后的输入值问题
解决你的Angular表单修改与网络请求问题
看起来你的代码里有几个关键问题导致了网络错误和无法正确获取修改后的内容,我来帮你一步步修复:
问题分析
- 数据绑定不匹配:模板里绑定的是单独的
title/body变量,但editForm方法里用的是this.post对象,两者没有关联,导致修改后this.post还是初始值,请求数据错误。 - 请求ID错误:
this.post.id初始为0,你没有把从API获取到的post数据赋值给this.post,导致PUT请求的URL是posts/0(JSONPlaceholder的post ID从1开始,这个ID不存在,返回404错误)。 - API响应处理问题:如果你的
formService.getForms是获取单个post,那返回的是单个对象而非数组,posts[0]会导致this.forms变成undefined,无法正确赋值标题和正文。
解决方案
1. 修正数据绑定,统一使用post对象
把模板里的[(ngModel)]绑定到post对象的属性,这样修改输入框内容时,this.post会自动同步更新:
<div class="forms container"> <form #postForm="ngForm"> <div class="form-group"> <label for="title">Title</label> <input [(ngModel)]="post.title" name="title" id="title" type="text" class="form-control" > </div> <div class="form-group"> <label for="body">Body</label> <textarea [(ngModel)]="post.body" name="body" id="body" cols="30" rows="10" class="form-control" ></textarea> </div> <button class="btn btn-success" (click)="editForm()">Submit</button> </form> </div>
2. 正确初始化post对象
在ngOnInit里,把API返回的post数据直接赋值给this.post,确保它包含正确的id、userId等关键信息:
ngOnInit() { this.id = this.route.snapshot.params['id']; // 假设你的formService.getForms是根据ID获取单个post,如果是返回数组,需要调整服务逻辑 this.formService.getForms(this.id).subscribe( (post: form) => { this.post = post; console.log('获取到的原始数据:', post); } ); }
如果你的formService当前是返回所有posts的数组,建议修改服务方法来直接获取单个post:
// 在form.service.ts中 getForms(id: number): Observable<form> { return this.http.get<form>(`https://jsonplaceholder.typicode.com/posts/${id}`); }
3. 修正editForm方法,正确发送请求并打印修改内容
现在this.post已经包含修改后的内容,直接使用它发送请求,同时在请求前打印你需要的修改后数据:
editForm(){ // 先打印修改后的标题和正文,满足你的需求 console.log('修改后的标题:', this.post.title); console.log('修改后的正文:', this.post.body); // 用Angular HttpClient发送请求(更符合框架最佳实践) this.http.put(`${this.formsUrl}/${this.post.id}`, this.post, { headers: { "Content-type": "application/json; charset=UTF-8" } }).subscribe( json => console.log('API返回的修改后数据:', json), error => console.error('请求错误:', error) // 捕获错误方便调试 ); }
这样修改后,点击提交按钮时,你就能看到修改后的标题和正文被打印出来,同时PUT请求会发送到正确的URL,不会再出现404错误。
内容的提问来源于stack exchange,提问作者y3v2btr93iq
相关产品推荐
相关产品推荐

