Angular API新增数据时报错:ERROR TypeError: _co.post未定义
解决Angular中“ERROR TypeError: _co.post is not defined”的问题
嘿,我来帮你搞定这个报错!这个错误的核心问题是你的组件里post属性没有被正确初始化,导致模板在尝试绑定post.title和post.body时找不到这个对象。
错误原因分析
在post.component.ts里,你对post的写法是:
post:{ id:0, title:'', body:'', userId:'' };
这其实是在给post指定TypeScript类型注解,但并没有实际给它赋值一个对象。组件初始化后,post的值是undefined,模板里访问post.title自然会抛出“_co.post is not defined”的错误(_co是Angular模板里对组件实例的引用)。
解决方案步骤
1. 正确初始化post对象
修改post.component.ts里的post属性定义,把类型注解改成实际的对象赋值:
// 原来的错误写法 // post:{ id:0, title:'', body:'', userId:'' }; // 修改后的正确写法 post = { id: 0, title: '', body: '', userId: '' };
这样组件初始化时post就会是一个带初始值的对象,模板绑定就能正常工作了。
2. 修复表单默认提交行为(可选但推荐)
你的表单按钮是type="submit",点击后会触发浏览器默认的表单提交行为,导致页面刷新。可以通过以下两种方式解决:
方式一:修改按钮类型为button
<button (click)="createPost()" type="button" class="btn btn-primary">Submit</button>
方式二:使用Angular表单提交事件并阻止默认行为
在模板的form标签上添加ngSubmit事件:
<form (ngSubmit)="createPost($event)"> <!-- 表单内容不变 --> <button type="submit" class="btn btn-primary">Submit</button> </form>
然后在组件的createPost方法中阻止默认行为:
createPost(event: Event){ // 阻止浏览器默认提交刷新 event.preventDefault(); this.http.post('https://jsonplaceholder.typicode.com/posts',this.post) .subscribe(response=>{ console.log(response.json()) }) }
修改后的完整代码
post.component.ts
import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'posts', templateUrl: './posts.component.html', styleUrls: ['./posts.component.css'] }) export class PostsComponent implements OnInit { posts:any[]=[]; // 正确初始化post对象 post = { id: 0, title: '', body: '', userId: '' }; constructor( private http:Http ) { this.http.get('https://jsonplaceholder.typicode.com/posts') .subscribe(Response=>{ this.posts=Response.json() }); } ngOnInit() { } createPost(event: Event){ event.preventDefault(); this.http.post('https://jsonplaceholder.typicode.com/posts',this.post) .subscribe(response=>{ console.log(response.json()) }) } }
post.component.html
<form (ngSubmit)="createPost($event)"> <legend>New post</legend> <div class="form-group"> <label for="title">Title</label> <input [(ngModel)]="post.title" type="text" name="title" id="title" class="form-control" placeholder="title"> </div> <div class="form-group"> <label for="body">Body</label> <textarea [(ngModel)]="post.body" name="body" id="body" class="form-control" placeholder="body"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <p>{{ post | json }}</p> <ul class="list-group"> <li class="list-group-item" *ngFor="let post of posts"> <h4>{{ post.title }}</h4> <p>{{ post.body }}</p> </li> </ul>
做完这些修改后,你的新增数据功能应该就能正常工作,不会再抛出那个错误啦!
内容的提问来源于stack exchange,提问作者Najib Marzouk
相关产品推荐
相关产品推荐

