My first CRUD with Angular FIre v16 and Angular v16

463 views
Skip to first unread message

Loris Dal Santo

unread,
Nov 27, 2023, 12:37:39 PM11/27/23
to Firebase Google Group

Hello everyone,

I'm trying to create my first CRUD on Firebase with Angular v14 and Angular Fire v16, but it's not working. Any guides or information? I've already checked all the Firebase guides, but I'm encountering this error:

"@firebase/firestore: Firestore (10.6.0): Could not reach Cloud Firestore backend. Connection failed 1 time. Most recent error: FirebaseError: [code=failed-precondition]: The Cloud Firestore API is not available for Firestore in Datastore Mode database projects/name/databases/(default). This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend."

Any guides or help on accessing the real-time database?

Thanks a lot to everyone for the response.

- app.module:
imports: [
    BrowserModule,
    provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
    provideFirestore(() => getFirestore()),
    provideDatabase(() => getDatabase()),
    provideStorage(() => getStorage()),
    AngularFirestoreModule.enablePersistence(),
    AngularFireModule.initializeApp(environment.firebaseConfig),
]

- db service:
// firebase-database.service.ts
import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreCollection,
  AngularFirestoreDocument,
} from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';
import { Article } from '../models/article.model';

@Injectable({
  providedIn: 'root',
})
export class FirebaseDatabaseService {
  private articlePath = '/articles';
  private articleCollection: AngularFirestoreCollection<Article>;

  constructor(private db: AngularFirestore) {
    this.articleCollection = db.collection(this.articlePath);
    console.log(this.articleCollection)
  }

  getAll(): AngularFirestoreCollection<Article> {
    return this.articleCollection;
  }

  async create(data: Article): Promise<any> {
    if (!data) {
      throw new Error('Data is required');
    }

    try {
      const docRef = await this.articleCollection.add({ ...data });
      console.log('Document written with ID:', docRef.id);
      return docRef;
    } catch (error) {
      console.error('Error adding document:', error);
      throw error;
    }
  }

  update(id: string, data: any): Promise<void> {
    if (!id || !data) {
      throw new Error('ID and data are required');
    }

    return this.articleCollection.doc(id).update(data);
  }

  delete(key: string): Promise<void> {
    if (!key) {
      throw new Error('Key is required');
    }

    return this.articleCollection.doc(key).delete();
  }
}

- component 1:
saveArticle() {
    if (this.articleForm.valid) {
      this.firebaseDBService
        .create(this.articleForm.value)
        .then(() => {
          console.log('Article saved successfully');
          this.resetArticle();
        })
        .catch((error) => {
          console.error('Error saving article:', error);
        });
    } else {
      console.error('Article form is not valid');
    }
  }

- list:
// article-list.component.ts
import { Component, OnInit } from '@angular/core';
import { ArticleService } from 'src/app/service/article.service';
import { Article } from 'src/app/models/article.model';
import { FirebaseDatabaseService } from 'src/app/service/firebase-database.service';
import { map } from 'rxjs';

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.scss'],
})
export class ArticleListComponent implements OnInit {
  articles?: Article[];
  currentArticle?: Article;
  currentIndex = -1;
  title = '';

  constructor(
    private articleService: ArticleService,
    private firebaseDbSevice: FirebaseDatabaseService
  ) {}

  ngOnInit(): void {
    this.loadArticles();
  }

  refreshList(): void {
    this.currentArticle = undefined;
    this.currentIndex = -1;
    this.loadArticles();
  }

  loadArticles(): void {
    this.firebaseDbSevice
      .getAll()
      .snapshotChanges()
      .pipe(
        map((changes) =>
          changes.map((c) => ({
            id: c.payload.doc.id,
            ...c.payload.doc.data(),
          }))
        )
      )
      .subscribe((data) => {
        this.articles = data;
      });
  }

  setActiveArticles(article: Article, index: number): void {
    this.currentArticle = article;
    this.currentIndex = index;
  }
}
Reply all
Reply to author
Forward
0 new messages