AngularFirestore使文档详细信息无效

时间:2018-02-21 22:39:38

标签: javascript angular firebase google-cloud-firestore angularfire2

我目前正在制作一个简单的Angular产品列表网站。我已将我的应用程序连接到Firebase并使用了AngularFirestore。我有一个产品组件,列出了我的所有产品,当用户选择产品时,它会将产品ID重新定向到产品组件。

我正在尝试使用产品组件上的ID获取产品详细信息,但不会100%获得产品详细信息。

我是棱角分明的新手,我觉得我在这里做错了。

product.component.ts

import { Component, OnInit } from '@angular/core';
import { ProductService } from '../services/product.service';
import { Product } from '../product-model';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {
  product?: Product;
  id: any;

  constructor(
    private productService: ProductService,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.id = this.route.snapshot.params['id'];
    this.productService.getProducts().subscribe(products =>{
      this.product = products.find(a => a.id === this.id);
    })
  }
}

product.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Product } from '../product-model';
import { Observable } from 'rxjs/Observable';



@Injectable()
export class ProductService {
  productsCollection: AngularFirestoreCollection<Product>;
  products:Observable<Product[]>;
  productDoc:AngularFirestoreDocument<Product>;

  result:any;

  constructor(public angularFirestore:AngularFirestore) { 
    this.productsCollection = this.angularFirestore.collection('products');
    this.products = this.productsCollection.snapshotChanges().map(changes =>{
      return changes.map(a => {
        const data = a.payload.doc.data() as Product;
        data.id = a.payload.doc.id;
        return data;
      });
    });
   }

   getProducts(){
     return this.products;
   }

   addProduct(product:Product){
     this.productsCollection.add(product);
   }

   getProductDetails(id){
     this.productsCollection.snapshotChanges().subscribe(product =>{
       return product.find(a => a.payload.doc.id === id);
     })
   }
}

我想知道我做错了什么。非常感谢你。

0 个答案:

没有答案