angular - 检索单个对象 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">×</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>
解决方案
试试这样:
零件
this.newsService.getSingleNews(this.id).subscribe(news => {
this.news = news
});
服务.ts
好像你在新闻之后错过了一个斜线。
getSingleNews(id: string) {
return this.db.object('news/' + id);
}
更新:
将属性更改news: Observable<any>
为对象。如果您按照我向您展示的方式进行操作,则不再是可观察的。
推荐阅读
- python - /srv/share/ykant3/pythia/vector_cache/wiki.en.bin 无法打开加载
- python - Python调度-如何每5分钟从HTML中提取数据
- javascript - 如何将 SortableJS 位置保存到对象?
- tableau-api - Tableau:空行的总和
- java - Maven 阴影插件 - 不要重新定位排除/可选范围依赖项
- javascript - 如果包含相同类型的类或标识符,则对重复的输入值求和
- spring-boot - 为什么使用 ApplicationContextRunner 在失败的上下文测试中从未调用过 ConditionEvaluationReportLoggingListener?
- django - DRF ListAPIView 返回多对多值名称而不是 pk
- javascript - 我如何在反应中取消订阅
- c# - 由于在 abp.io 框架上工作,我收到 Http 错误 404