我正在跟踪一个教程,其中一个人演示了如何使用新闻API使用ionic 4构建新闻应用。我还想创建一个新闻应用程序,以显示来自特定主题的不同来源的摘要新闻,但是问题是我正在考虑为此目的使用Firebase Cloud Firestore而不是使用新闻API,并且我不知道如何从Firestore集合中获取数据。您可以查看以下代码以供参考。
news.page.ts
import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-news',
templateUrl: './news.page.html',
styleUrls: ['./news.page.scss']
})
export class NewsPage implements OnInit {
data: any;
page = 1;
constructor(private newsService: NewsService, private router: Router) {}
ngOnInit() {
this.newsService
.getData(`top-headlines?country=us&category=business&pageSize=5&page=${this.page}`)
.subscribe(data => {
console.log(data);
this.data = data;
});
}
onGoToNewsSinglePage(article) {
this.newsService.currentArticle = article;
this.router.navigate(['/news-single']);
}
}
news.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient } from '@angular/common/http';
const API_URL = environment.apiUrl;
const API_KEY = environment.apiKey;
@Injectable({
providedIn: 'root'
})
export class NewsService {
currentArticle: any;
constructor(private http: HttpClient) { }
getData(url) {
return this.http.get(`${API_URL}/${url}&apiKey=${API_KEY}`);
}
}
news.page.html
<ion-header>
<ion-toolbar>
<ion-title>News</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-card *ngFor="let article of data?.articles" (click)="onGoToNewsSinglePage(article)">
<!-- <ion-img [src]="article.urlToImage"></ion-img> -->
<ion-card-content>
<ion-card-title>{{article.title}}</ion-card-title>
<p>{{article.description}}</p>
</ion-card-content>
</ion-card>
</ion-content>
我已经在我的项目中安装了angularfire 2插件,将所有文件导入了app.module.ts中,并且还为所有Firebase详细信息准备了一个配置文件。我只想知道如何从Firebase集合中获取数据并将其绑定到html代码。