错误TypeError:无法设置未定义的属性“作者”

时间:2018-08-06 09:57:08

标签: angular6 jsondb

当我想保存更改以通过单击“提交”按钮保存服务器“添加评论”时出现此错误,谢谢您的帮助

onSubmit() {      
this.comment.author = this.author;
this.comment.rating = this.rating;
this.comment.comment = this.comment1;


this.comment.date = new Date().toISOString();
console.log(this.comment);
this.dishcopy.comments.push(this.comment);
this.dishcopy.save()
  .subscribe(dish => { this.dish = dish; console.log(this.dish); });

  }

模板代码:

    <div class="example-container">
  <mat-form-field>
    <input matInput placeholder="author" [(ngModel)]="author">
  </mat-form-field>
  <mat-form-field>
    <mat-select placeholder="rating" [(ngModel)]='rating'>
      <mat-option value="1">1</mat-option>
      <mat-option value="2">2</mat-option>
      <mat-option value="3">3</mat-option>
      <mat-option value="4">4</mat-option>
      <mat-option value="5">5</mat-option>
    </mat-select>
  </mat-form-field>
  <mat-form-field>
    <textarea matInput placeholder="comment" [(ngModel)]="comment1"></textarea>
  </mat-form-field>
  <button (click)="onSubmit()">Submit</button>
</div>

更多细节: 这是Comment.ts代码:

export class Comment {
rating: number;
comment: string;
author: string;
date: string;}

我通过以下方式实例化它:

import { Comment } from '../shared/comment';
...
comment:Comment;

1 个答案:

答案 0 :(得分:1)

似乎您从未实例化this.comment,因此,当您尝试访问其author属性时,会发现它未定义。

将此代码添加到onSubmit()的开头

this.comment = new Comment();

请记住,如果您不需要对onSubmit()进行某些检查或逻辑运算,则可以将this.comment的属性直接绑定到模板变量

编辑

此代码comment:Comment;不是实例,是  声明。您需要这个:

comment: Comment = new Comment();

或通过让TypeScript推断类型来实现:

comment = new Comment();