Firebase Cloud Firestore无法加载数据

问题描述 投票:5回答:1

当我打开网页数据显示,但我更改组件并返回此组件数据不显示。它显示没有项目。我检查日志但没有运行到ngOnIt。 ngOnIt在web strat或web reload上运行。

这是stock.service.ts

import { Injectable } from '@angular/core';

import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

import { Observable } from 'rxjs/Observable';
import { Stock } from './stock.model';

@Injectable()
export class StockService {

  stocksCollection: AngularFirestoreCollection<Stock>;
  stocks: Observable<Stock[]>;

  constructor(public afs: AngularFirestore) {
    this.stocks = this.afs.collection('stocks').valueChanges();
  }
  getStock(){
    return this.stocks;
  }
}

stock.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute,Params } from '@angular/router';

import { StockService } from '../shared/stock.service';
import { Stock } from '../shared/stock.model';
import { Brands } from '../shared/brand';

import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-stock',
  templateUrl: './stock.component.html',
  styleUrls: ['./stock.component.css']
})
export class StockComponent implements OnInit {

  stocks: Stock[];
  brand: Brands;
  sub: Subscription;
  brand_name: string;

  constructor(
    private stockService: StockService,
    private router: ActivatedRoute
  ) { }

  ngOnInit() {
    this.stockService.getStock().subscribe(stocks => {
      console.log(stocks);
      this.stocks = stocks;
    });

    this.sub = this.router.params.subscribe(params =>{
      this.brand_name = params['brand'];
    });

    console.log('Brand : '+this.brand_name);
  }

}

和stock.component.html

<div *ngIf="stocks != null || stocks?.length > 0 ; else noStocks" >
  <ul *ngFor="let item of stocks" class="collection">
    <li class="collection-item " >{{item.name}} | {{item.brand}} | {{item.price}}</li>
  </ul>
</div>

<ng-template #noStocks>
  <p>no item</p>
</ng-template>

我不知道代码哪里出错了。谢谢你的答案。

html angular typescript google-cloud-firestore
1个回答
4
投票

不要在服务的构造函数内部加载,在方法中移动它

  constructor(public afs: AngularFirestore) {

  }
  getStock(){
    this.stocks = this.afs.collection('stocks').valueChanges();
    return this.stocks;
  }
© www.soinside.com 2019 - 2024. All rights reserved.