【问题标题】:Firebase Cloud Firestore can not load dataFirebase Cloud Firestore 无法加载数据
【发布时间】:2018-08-11 12:50:54
【问题描述】:

当我打开网络数据时显示,但我更改组件并返回此组件数据不显示。它不显示任何项目。我检查日志但没有运行到 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】:

    不要在服务的构造函数中加载,将其移动到方法中

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

    【讨论】:

    • 谢谢先生!但可以解释为什么会发生这种情况,而不是在 firebase 的实时数据库上?
    猜你喜欢
    • 2019-10-29
    • 2021-05-01
    • 1970-01-01
    • 2021-06-19
    • 2018-04-17
    • 2023-03-09
    • 1970-01-01
    • 2021-11-05
    • 2020-02-01
    相关资源
    最近更新 更多