Angular报错:Cannot set properties of undefined (setting 'tags')求助
错误根源
你只声明了createIssue!:Issue;但没实例化这个对象,它初始值是undefined,所以往this.createIssue.tags赋值时直接报错。另外,split(',')本身就返回数组,用Array()包裹会生成嵌套数组(比如输入"a,b"会变成[["a","b"]]),不符合API要求的数组格式。
修复步骤
1. 先实例化Issue对象
在AddIssue()方法开头先创建Issue实例,或者在声明时直接初始化:
// 方法一:在AddIssue开头添加 this.createIssue = new Issue(); // 方法二:替换原声明语句 createIssue:Issue = new Issue();
2. 正确处理tags数组
把原tags赋值代码改成下面的写法,同时处理空输入和标签空格:
const tagsInput = this.createIssueForm.value.tags || ''; this.createIssue.tags = tagsInput.split(',').map(tag => tag.trim());
这样输入空值时会得到空数组,输入带空格的标签(比如"bug, feature")也会自动去除前后空格,更符合API要求。
3. 完整修复后的AddIssue方法
AddIssue(){ console.log(this.createIssueForm.value); // 实例化Issue对象 this.createIssue = new Issue(); // 处理tags const tagsInput = this.createIssueForm.value.tags || ''; this.createIssue.tags = tagsInput.split(',').map(tag => tag.trim()); console.log(this.createIssue.tags); this.createIssue.status = "1"; this.createIssue.summary = this.createIssueForm.value.summary; this.createIssue.priority = this.createIssueForm.value.priority; this.createIssue.description = this.createIssueForm.value.description; this.createIssue.sprint = this.createIssueForm.value.sprint; this.createIssue.storypoint = this.createIssueForm.value.storypoint; this.createIssue.type = this.createIssueForm.value.type; this.createIssue.assignee = this.createIssueForm.value.assignee; this.createIssue.projectID = this.createIssueForm.value.projectID; console.log(this.createIssue); this.apiService.createIssue(this.createIssue) .subscribe( response=>{ console.log(response); alert("Issue Created"); }); }
额外优化(可选)
用对象展开语法简化属性赋值,减少重复代码:
AddIssue(){ console.log(this.createIssueForm.value); const tagsInput = this.createIssueForm.value.tags || ''; // 直接合并表单值和固定字段,自动实例化 this.createIssue = { ...this.createIssueForm.value, status: "1", tags: tagsInput.split(',').map(tag => tag.trim()) } as Issue; console.log(this.createIssue); this.apiService.createIssue(this.createIssue) .subscribe( response=>{ console.log(response); alert("Issue Created"); }); }
内容的提问来源于stack exchange,提问作者Nitin Saini
相关产品推荐
相关产品推荐

