我正在尝试从firebase数据库中获取产品数据,并在浏览器中显示其属性。我最初将product
对象定义为空,当我从firebase获取数据时,然后使用类似[(ngModel)]="product.title"
的双向绑定来显示它。但是得到上述错误。请帮忙。
产品服务.ts
getProduct(productId){
return this.db.object('/products/' + productId ).valueChanges();
}
}
产品组成.ts
export class ProductFormComponent implements OnInit{
categories$;
product={};
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.getProduct(id).pipe(take(1)).subscribe(p => this.product = p);
}
product-form-component.html
<div class = "row">
<div class="col-md-6">
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" name="title"
type="text" class="form-control" placeholder="Name of the Product"
id="title" required> <!-- Error [(ngModel)]="product.title" , Property 'title' does not exist on type '{}'-->
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required
</div>
</div>
您已将类型定义为any
。更好的方法是定义类型,或者简单地让typescript推断类型,比如
export class ProductFormComponent implements OnInit{
categories$ = categoryService.getCategories();
product = {
title: ''
}
constructor(
private router: Router,
private route :ActivatedRoute,
private categoryService: CategoryService,
private productService:ProductService) {
let id = this.route.snapshot.paramMap.get('id');
if (id) {
this.productService.getProduct(id).pipe(
take(1)
).subscribe(p => this.product = p);
}
}
为产品对象创建一个接口,并将类型添加到product
变量
interface Product {
title: string
// otherProps: string
}
export class ProductFormComponent implements OnInit {
categories$ = categoryService.getCategories();
// added a definite assertion telling TS that it will be assigned before access
private product!: Product
constructor(
private router: Router,
private route :ActivatedRoute,
private categoryService: CategoryService,
private productService:ProductService
) {
let id = this.route.snapshot.paramMap.get('id');
if (id) {
this.productService.getProduct(id).pipe(
take(1)
).subscribe(p => this.product = p);
}
}
}