微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – Firebase Cloud Firestore无法加载数据

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

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

解决方法

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

constructor(public afs: AngularFirestore) {

  }
  getStock(){
    this.stocks = this.afs.collection('stocks').valueChanges();
    return this.stocks;
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐