Двухсторонняя привязка, показывающая в Angular5, показывающая TypeError: Невозможно прочитать свойство 'title' из null - PullRequest
0 голосов
/ 13 мая 2018

Я делаю форму в Angular5, используя firebase в бэкэнде для моей учебной цели.Моя двусторонняя привязка не работает.Это дает мне ошибку ниже на консоли.

TypeError: Cannot read property 'title' of null

Вот мой шаблон:

<form #f="ngForm" (ngSubmit)="save(f.value)">        
        <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 mt-1" *ngIf="title.touched && title.invalid">
              Title is required.
            </div>
          </div>
    <!-- other input fields here -->
    </form>

Вот мой компонент:

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

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
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();
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
      this.productService.get(id)
        .take(1).subscribe(p => this.product = p);
      // this is coming empty
      console.log(this.product);
    }
  }

  ngOnInit() {
  }

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

}

А вотСлужба:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product) {
    return this.db.list('/products').push(product);
  }

  getAll() {
    return this.db.list('/products').snapshotChanges().map(categories => {
      return categories.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
  }

  get(productId) {
       return this.db.object('/products' + productId).valueChanges();
    }
}

Пожалуйста, объясните мне, что не так с моим кодом.Я новичок в угловой.Я не могу решить это.Пожалуйста, помогите.

1 Ответ

0 голосов
/ 13 мая 2018

причина исключения в том, что свойство продукта не определяется при инициализации dom.

есть два варианта решения проблемы:

*ngif вся форма.

используйте ? такой оператор:

<input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...