错误TypeError:无法读取未定义的属性“title” [英] ERROR TypeError: Cannot read property 'title' of undefined

查看:75
本文介绍了错误TypeError:无法读取未定义的属性“title”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与这些代码块作斗争,甚至当我尝试将其初始化为对象时,我也会遇到错误。

I've been battling with these block of codes for some days, and even when i try initializing it as an object i get errors.

这是我的restaurantForm .ts文件

this is my restaurantForm.ts file

import { Component, OnInit } from '@angular/core';
import {RestaurantService} from '../../restaurant.service';
import {ProductService} from '../../product.service';
import {ActivatedRoute, Router} from '@angular/router';
import 'rxjs/add/operator/take';
import {Product} from '../../model/product';

@Component({
  selector: 'app-product-form',
  templateUrl: './restaurant-form.component.html',
  styleUrls: ['./restaurant-form.component.css']
})
export class RestaurantFormComponent implements OnInit {
  restaurants$;
  id;
  product: Product;
  constructor(private restaurantService: RestaurantService,
              private productService: ProductService,
              private route: ActivatedRoute,
              private router: Router) {
    this.restaurants$ = this.restaurantService.getAll();
    this.id = this.route.snapshot.paramMap.get('id');
    if (this.id) {
      this.productService.get(this.id).take(1).subscribe(p => this.product = p);
    }
   this.product = new Product();
  }
  save(product) {
    if (this.id) {
      this.productService.update(this.id, product);
    } else {
      this.productService.create(product);
    }
    this.router.navigate(['/admin/restaurants']);
  }
  delete() {
    if (!confirm('Are you sure you want to delete this product?')) { return ; }
      this.productService.delete(this.id);
      this.router.navigate(['/admin/restaurants']);
  }

  ngOnInit() {
  }

}

这是我的产品型号

export interface Product {
  $key: string;
  title: string;
  price: number;
  restaurant: string;
  imageUrl: string;

}

我的restaurantForm.html

My restaurantForm.html

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <form #f="ngForm" (ngSubmit)="save(f)">
        <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-danger alert" *ngIf="title.touched && title.invalid">
            Title is required.
          </div>
        </div>
        <div class="form-group">
          <label for="price">Delivery Price</label>
          <div class="input-group">
            <span class="input-group-addon">₦</span>
            <input #price="ngModel" [(ngModel)]="product.price" name="price" id="price"
                   type="number" class="form-control" required [min]="0">
          </div>
          <div class="alert alert-danger" *ngIf="price.touched && price.invalid">
            <div *ngIf="price.errors.required">
              Delivery Price is required
            </div>
            <div *ngIf="price.errors.min">
              Delivery Price should be 0 or higher.
            </div>
          </div>
        </div>
        <div class="form-group">
          <label for="restaurant">Restaurant</label>
          <select #restaurant="ngModel" [(ngModel)]="product.restaurant" name="restaurant" id="restaurant" class="form-control" required>
            <option value=""></option>
            <option *ngFor="let r of restaurants$ | async" [value]="r.$key">
              {{ r.name }}
            </option>
          </select>
          <div class="alert alert-danger" *ngIf="restaurant.touched && restaurant.invalid">
            Please select a restaurant.
          </div>
        </div>
        <div class="form-group">
          <label for="imageUrl">Image Url</label>
          <input #imageUrl="ngModel" [(ngModel)]="product.imageUrl" name="imageUrl"
                 id="imageUrl" type="text" class="form-control" required url>
          <div class="alert alert-danger" *ngIf="imageUrl.touched && imageUrl.invalid">
            <div *ngIf="imageUrl.errors.required">Image Url is required.</div>
            <div *ngIf="imageUrl.errors.url">Please enter a valid Url.</div>
          </div>
        </div>
        <button  class="btn btn-primary">Save</button>
        <button type="button" (click)="delete()" class="btn btn-danger">Delete</button>
      </form>
    </div>
    <div class="col-md-6">
     <app-product-card [product]="product" [showActions]="false"></app-product-card>
    </div>
  </div>
 </div>

我的价格出现同样的错误, $ key,restaurant和imageUrl。
提前感谢。虽然我查找了一些解决方案,说我应该使用elvis运算符,例如'product?.title',这种方法仍然有效。

I get the same errors with price, $key, restaurant and imageUrl. thanks in advance. Although Ive looked up some solutions saying i should use elvis Operator e.g 'product?.title' this method isnt still working.

推荐答案

由于产品 undefined ,您需要使用 构造函数中的空对象声明并初始化它 ngOninit

Because product is undefined, you need to declare and initialize it with empty object inside the constructor or ngOninit.

编辑:

您需要在组件中声明产品,

You need to have the Product declared in the component as,

const product : Produce = {  $key: "", title: "",price:0,restuarant :"" ,imageurl:"" };

这篇关于错误TypeError:无法读取未定义的属性“title”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆