我需要帮助。.我有一个服务组件,该组件按以下方式获取数据..但我想在其他组件上重用它以仅显示特定类别。
当我单击链接时,我试图实现它仅在选择了类别链接时才会显示。
像例子。
类别:{牛奶,肉,水果}
MODEL.TS
export interface Product {
id?: string;
category: string;
name: string;
price: number;
image:string;
description: string;
}
服务。 TS
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection,
AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Product } from '../model/Product';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ProductService {
productCollection: AngularFirestoreCollection<Product>;
product: Observable<Product[]>;
productDoc: AngularFirestoreDocument<Product>;
filter
constructor(private afs: AngularFirestore) {
this.productCollection = this.afs.collection('Product');
}
getProducts() {
return this.product = this.productCollection.snapshotChanges().pipe(map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Product
const id = a.payload.doc.id;
return { id, ...data }
})
}))
}
addProduct(data: Product) {
this.productCollection.add(data);
}
// to navigate into edit
getProductData(id: string) {
this.productDoc = this.afs.doc<Product>(`Product/${id}`)
return this.productDoc.valueChanges()
}
// to delete need to get id
getProduct(id: string) {
return this.afs.doc<Product>(`Product/${id}`)
}
delete(id: string) {
return this.getProduct(id).delete()
}
updateProduct(id, formData) {
return this.getProduct(id).update(formData)
}
}
COMPONENT.TS
import { ProductService } from './../../service/product.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Product } from 'src/app/model/Product';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-aquatic',
templateUrl: './aquatic.component.html',
styleUrls: ['./aquatic.component.css']
})
export class AquaticComponent implements OnInit {
products: Observable<Product[]>;
constructor( private productService: ProductService) { }
ngOnInit() {
this.products = this. productService.getProducts();
}
}
COMPONENT.HTML
<div *ngFor="let product of products | async">
<p> {{ product.category}}</p>
<p> {{ product.name }}</p>
<p> <img src="{{ product.image }}"> </p>
</div>