简体   繁体   中英

How to use cloud firestore to get data in an ionic 4 app

I was following a tutorial where a guy showed how to build a news app with ionic 4 using the news API. I also want to create a news app that shows summarized news from different sources on a particular topic but the problem is that I am thinking of using the Firebase cloud firestore for this purpose instead of using the news API and I can't figure out how to get the data from the firestore collection. You can look at the following code for reference.

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>

I have installed the angularfire 2 plugin in my project, imported all the files in app.module.ts and also prepared a config file for all the Firebase details. I just want to know how to get the data from Firebase collection and bind it to the html code.

Instead of calling your service this.newsService.getData(...) you will have to use firebase service public AngularFirestore from angularfire2/firestore . Here is an example:

Import the service and inject it in your component news.page.ts :

import {AngularFirestore} from 'angularfire2/firestore';
...
data: any;
constructor ( public db: AngularFirestore ) {
  }
...

To retrieve a single post, create the function

getPostEntry ( postTitle: string ): Observable<any> {
    return this.db.collection<any> ( "posts" , ref => ref.where ( 'title' , '==' , postTitle ) ).valueChanges ();
  }

This will search all entries in your firestore collection called "posts" with attribute title being your postTitle .

Simillarly to retrieve all posts

getAllPosts (): Observable<any> {
    return this.db.collection<any>( "post" ).valueChanges ();
  }

Then invoke the functions and consume the observables. For instance you can do it in your ngOnInit:

ngOnInit() {
            this.getAllPosts().subscribe((data)=>{
                this.data = data;
                console.log(data);
            });
        }

Now you have your data in your variable data , you just have to draw it in your html as you would normally do. Have in mind that it will probably be an array with all your posts (if there are any).

here is a gist with the code I edited from your class:

https://gist.github.com/HugoJBello/73fb3c5c0964f29934a2d8021efb128d

EDIT

renamed firebase collection and added subscription to observable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM