Search code examples
angularfirebaseangularfire2angular6

Error in adding in-line type in Angular6


I got this error when i try to add the product.ts interface so that i can enable the IntelliSense in the product filter method.

I was following this certain angular+firebase tutorial and i was stubborn that the tutorial's firebase and angularfire2 version is lower than my version.

Any help would be great :)

Error

enter image description here

admin-products.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ProductService } from '../../product.service';
import { Subscription } from '../../../../node_modules/rxjs';
import { Product } from '../../models/product';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit, OnDestroy {
  products: Product[];
  filteredProducts: any[];
  subscription: Subscription;

  constructor(private productService: ProductService) {
    this.subscription = this.productService.getAll()
      .subscribe(products => this.filteredProducts = this.products = products);
  }

  filter(query: string) {
    this.filteredProducts = (query) ?
      this.products.filter(p => p.title.toLowerCase().includes(query.toLowerCase())) : 
      this.products;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  ngOnInit() {
  }

}

model/product.ts

export interface Product {
    key: string;
    title: string;
    price: number;
    category: string;
    imageUrl: string;
}

product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { map, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

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

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

Solution

  • From the getAll method you are returning value of type {key: string}[]

    And you are assigning that to this.filteredProducts and this.products which are of different type Product.

    So you have to do one of the following according to your business requirement.

    1. make fields other than key optional in Product interface.
    2. Return value of Product type from getAll method.