检索单个对象Firebase Angular

时间:2018-11-15 23:17:27

标签: angular firebase angularfire2 angularfire

我正在开发此应用程序,但是在检索对象的全部信息时遇到了问题。

我有一个“新闻”页面,它将显示数据库中的所有列表,并且工作正常,当您单击新闻时,它将带您进入“详细信息”页面,我可以进行路由,没问题。

问题是我无法从Firebase获取数据。我在做什么错了?

谢谢

组件:

import { ActivatedRoute, Params, Router } from '@angular/router';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NewsService } from '../news.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class NewsDisplayComponent implements OnInit {
  @ViewChild('closeBtn') closeBtn: ElementRef;
  id;

  news: Observable<any>;

  constructor(private db: AngularFireDatabase, private route: ActivatedRoute, private newsService: NewsService, private router: Router) { }

  ngOnInit() {
    this.id = this.route.snapshot.params['id'];
    this.news = this.newsService.getSingleNews(this.id).valueChanges();
    console.log(this.news);
  }

  closeModal() {
    this.router.navigate(['/news']);
    this.closeBtn.nativeElement.click();
  }

}

Service.ts

import { map } from 'rxjs/operators';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { News } from './news.model';
import { Injectable } from '@angular/core';

@Injectable()
export class NewsService {
    news: AngularFireList<News[]>;
    constructor(private db: AngularFireDatabase) {
    }
    getNews() {
        this.news = this.db.list('news');
        return this.news.valueChanges();
    }

    getSingleNews(id: string) {
        return this.db.object('news' + id);
    }
}

HTML

<div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">{{ id }}</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" #closeBtn (click)="closeModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <h1>{{ news.title | async }}</h1>
        <h2>{{ news.subtitle | async }}</h2>
        <p>{{ news.article | async}}</p>
      </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

像这样尝试:

组件

this.newsService.getSingleNews(this.id).subscribe(news => {
    this.news = news
});

Service.ts

您似乎在新闻发布后想念自己了。

getSingleNews(id: string) {
    return this.db.object('news/' + id);
}

更新

news: Observable<any>属性更改为对象。如果按照我向您展示的方式进行操作,则不再是可观察的。