如何修复“无法读取未定义的属性"标题" [英] How to fix "Cannot read property 'title' of undefined"
本文介绍了如何修复“无法读取未定义的属性"标题"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在关注Mosh Hamedani教程"Angular 4:Pro的初学者".
I'm following Mosh Hamedani tutorial "Angular 4: Beginner to Pro".
我试图在编辑产品时以表格形式显示产品标题.产品存储在Firebase数据库中.我是Angular的新手.
I'm trying to show the title of a product in a form when trying to edit it. The product is stored in a firebase database. I'm new to Angular.
但是,当我进入编辑表单时,在控制台中出现此错误
However, I'm getting this error in the console when I go to the edit form
ERROR TypeError: Cannot read property 'title' of undefined
at Object.eval [as updateDirectives] (ProductFormComponent.html:7)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
at checkAndUpdateView (core.js:23307)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)
at callViewAction (core.js:23548)
at execEmbeddedViewsAction (core.js:23511)
at checkAndUpdateView (core.js:23308)
at callViewAction (core.js:23548)
这是我表格的一部分:
<div class="form-group">
<label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" <== error here
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>
这是product-form.component.ts
And here is the product-form.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CategoryService } from 'src/app/category.service';
import { ProductService } from 'src/app/product.service';
import { Router, ActivatedRoute } from '@angular/router';
import { take } from 'rxjs/operators';
@Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
product;
constructor(
categoryService: CategoryService,
private route: ActivatedRoute,
private productService: ProductService,
private router: Router) {
this.categories$ = categoryService.getCategories();
let id = this.route.snapshot.paramMap.get('id');
if (id) this.productService.get(id).snapshotChanges().pipe(take(1))
.subscribe(p => this.product = p); <== this does not seem to be working
}
save(product) {
this.productService.create(product);
this.router.navigate(["/admin/products"]);
}
ngOnInit() {
}
}
我该怎么做才能显示产品标题?
What can I do to show the product's title?
推荐答案
更改
product;
到
product:any = {};
和(valueChanges()而不是snapshotChnages())
and (valueChanges() instead of snapshotChnages())
if (id) this.productService.get(id).snapshotChanges().pipe(take(1))
.subscribe(p => this.product = p);
}
到
if (id) this.productService.get(id).valueChanges().pipe(take(1))
.subscribe(p => this.product = p); <== this does not seem to be working
}
已解决问题
这篇关于如何修复“无法读取未定义的属性"标题"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文