首页 > 解决方案 > 检索单个对象 Firebase Angular

问题描述

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

我有一个“新闻”页面,它将显示数据库中的所有列表,那个工作正常,当你点击新闻时,它会带你到“详细信息”页面,我可以做路由,没问题。

问题是我无法从 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();
  }

}

服务.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>

标签: angularfirebaseangularfire2angularfire

解决方案


试试这样:

零件

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

服务.ts

好像你在新闻之后错过了一个斜线。

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

更新:

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


推荐阅读