如何修复“无法读取未定义的 属性 'title'”

How to fix “Cannot read property 'title' of undefined”

我正在学习 Mosh Hamedani 教程“Angular 4:初学者到专业人士”。

我试图在尝试编辑时在表单中显示产品的标题。该产品存储在 firebase 数据库中。但是,当我转到编辑表单时,我在控制台中收到此错误:

ERROR TypeError: Cannot read property 'title' of null
    at ProductFormComponent_Template (product-form.component.html:6)
    at executeTemplate (core.js:7446)
    at refreshView (core.js:7315)
    at refreshComponent (core.js:8453)
    at refreshChildComponents (core.js:7108)
    at refreshView (core.js:7365)
    at refreshEmbeddedViews (core.js:8407)
    at refreshView (core.js:7339)
    at refreshComponent (core.js:8453)
    at refreshChildComponents (core.js:7108)

这里已经有人问过这个问题:,但是我尝试了提供的解决方案,但我仍然遇到同样的错误。 这是我表格的一部分:

            <div class="form-group">
                <label for="title">Title</label>
                <input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
                <div class="alert alert-danger" *ngIf="title.touched && title.invalid">
                    Title is Required.
                </div>
            </div>

这是 component.ts

export class ProductFormComponent implements OnInit {
  categories$;
  product: any = {};

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private categoryService: CategoryService,
    private productService: ProductService) { 
    this.categories$ = categoryService.getCategories();

    let id = this.route.snapshot.paramMap.get('id');
    if(id) this.productService.get(id).valueChanges().pipe(take(1)).subscribe(p => this.product = p);
    console.log(this.product);
  }

  save(product){
    this.productService.create(product);
    this.router.navigate(['/admin/products']);
  }

  ngOnInit(): void {
  }

}

编辑: 我使用 firebase 作为“后端”

它有一个简单的解决方案。显示错误是因为在初始化 html 组件时,产品尚未准备好(因为 api 调用需要一些时间来 return 数据),因此它是未定义的。因此在 html 组件中使用 ?. 如下所示。



    <div class="form-group">
                <label for="title">Title</label>
                <input #title="ngModel" [(ngModel)]="product?.title" name="title" id="title" type="text" class="form-control" required>
                <div class="alert alert-danger" *ngIf="title.touched && title.invalid">
                    Title is Required.
                </div>
            </div>

    ````

在产品后加问号,表示只有产品object可用时才取标题,即已经定义。

<div class="form-group"> <label for="title">Title</label> <input #title="ngModel" [(ngModel)]="product?.title" name="title" id="title" type="text" class="form-control" required> <div class="alert alert-danger" *ngIf="title.touched && title.invalid"> Title is Required. </div> </div>

ngIf 包装需要模型的元素可以解决问题。在模型准备好之前内容正在尝试渲染。

<ng-container *ngIf="_model">
    CONTENT HERE
</ng-container>