Retrieve data from Firestore once upon initialization of the app, and share it from that point forward

Previously, I utilized a mock that contained an array as the source of data for my entire app by iterating through it. The process worked well.

export const CASES: Case[] = [
  { id: 0,
    name: 'Diesel',
    portfolioImage: '/assets/images/portfolio/diesel.png',
    image: '/assets/images/diesel.jpg',
    image2: '/assets/images/diesel/diesel-sunflower.png',
    image3: '/assets/images/diesel/diesel-cap.png',
    link: '/cases/diesel',
    header: 'black'
  },

  { id: 1,
    name: 'WeWork Berlin',
    portfolioImage: '/assets/images/portfolio/berlin.png',
    image: '/assets/images/berlin.jpg',
    image2: '/assets/images/wework/berlin-logo.png',
    image3: '/assets/images/wework/berlin-building.png',
    link: '/cases/wework',
    header: 'white'
  }
];

Now, I am in the process of integrating my app with Firestore. To retrieve data from Firestore, I have implemented the following code within my desired component:

export class PortfolioComponent implements OnInit {

  cases;

  constructor(private db: AngularFirestore) { }

  ngOnInit() {
    this.db.collection('entries').valueChanges()
      .subscribe(val => this.cases = val);
  }

}

The current setup works, but my goal is to make this call only once - specifically, finding a way to fetch the data during app initialization...

  • and either merge it with the previous mock dataset,
  • or store the data in an array accessible globally

By doing this, my aim is to minimize fetching the data repeatedly and instead retrieve it once, consolidate it, and distribute it accordingly. Similar to how I managed it before integrating Firestore.

Answer №1

To retrieve data upon app initialization, the recommended approach is to utilize APP_INITIALIZER, which is a built-in instance of InjectionToken. An example implementation in app.module.ts would look like this:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppInitService } from './app-init.service';

export function initializeApp1(appInitService: AppInitService) {
  return (): Promise<any> => { 
    return appInitService.Init();
  }
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [ 
    AppInitService,
    { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true}
  ],
})
export class AppModule { }

Within your AppInitService, ensure that your data fetching request is made and stored properly. If you are using NGRX, store the data there, otherwise use a singleton root service. Make sure to return a promise that will resolve once the data is fetched.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AppInitService {

  constructor(private db: AngularFirestore, private dataService: DataService) { }

  Init(): Promise<any> {
     return new Promise((resolve, reject) => {
this.db.collection('entries').valueChanges()
      .subscribe(val => {
         this.dataService.data = val;
         resolve(true);
      });
     })
  }
}

After setting up the initialization process, inject dataService: DataService wherever needed to access the stored data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Struggling to locate root directory post-Angular 13 upgrade in Jest

After updating my project to Angular 13, I realized that Jest required some adjustments as well. Now, any mention of 'src' cannot be resolved properly. For instance: Cannot find module 'src/app/app.component/app.component.test' from & ...

Encountering unproductive errors with custom editor extension in VS Code

I'm currently developing a custom vscode extension for a read-only editor. During testing, I encountered a rather unhelpful error message. Can anyone offer some insight on what might be causing this issue? 2022-11-25 11:36:17.198 [error] Activating ex ...

Is it possible to create a Cypress report that only includes the successful test cases and excludes the failed ones?

Hello everyone, I trust you are well. Currently, I am seeking a solution to exclude failed test cases from Cypress XML report when using Junit as a reporter. The issue arises when importing test results into Jira, as failures create duplicate tests instead ...

"Exploring the Depths of Angular with Google Maps and Karma

After upgrading an Angular project from version 8 to 11 and updating the dependencies, I encountered an issue with compatibility. The project previously used the @agm/core package, which is not compatible with Angular 11. I replaced it with @angular/google ...

When sending a Post Request in Angular to a Spring Boot backend, a status code of 500 is

Encountering a 500 status code error while making the request below: createPost(postPayload: CreatePostPayload): Observable<any> { return this.http.post('http://localhost:8080/api/posts/', postPayload); } The request is successful wh ...

class-validator: ensures the correct number of digits are present in numeric values

Seeking assistance on validating the number of digits for numeric values using class-validator. Specifically, I want my entity to only accept numbers with 6 digits for a certain property. For example: const user1 = new User(); user1.code = 123456 // should ...

An error with code -4058 is preventing the installation of npm packages when running the 'npm install' command after using 'ng new'

Embarking on a new Angular project, I encountered an issue while trying to install packages listed in my package.json file. Despite multiple attempts on both of my computers, the same error persisted, leaving me baffled. Determined not to give up, I seek g ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

How to display an object in the template that does not have a specified property

I am dealing with an object that can have a type of WithBalance | WithoutBalance withBalance : { balance:number, name:string } withoutBalance : { name : string} <span>{{object?.balance ?? 0}} </span> However, when I attempt to access the bal ...

The parameters 'event' and 'event' are not compatible with each other due to their different types

I am currently working on an employee monitoring project that consists of multiple components. One specific component involves grouping together a set of buttons. While integrating these buttons in another component, I encountered an error in my code: The ...

Change the default icon in mat-stepper angular material

I'm attempting to customize the default edit icon in Angular Material's stepper component, but my attempts have been unsuccessful. Here is what I have tried: <mat-horizontal-stepper [linear]="isLinear" #stepper> <mat-step> ...

The function res.send() is returning a null object

I am facing an issue where the person object I am trying to send back using res.send() from the express backend to the angular frontend is always null. This data is being sent from the express backend at localhost/8081 to the angular frontend at localhost/ ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Disabling lint in a PhpStorm or WebStorm project with angular-cli

I am currently using PhpStorm version 2017.2, and I have created an angular-cli project within a directory that already contains several modules and components built with angular-cli. The issue I am facing is that I am inundated with countless linting err ...

Is there a way for me to determine the version of Angular that I am currently using?

Is there a way for me to figure out which version of Angular I am currently using? I attempted the following: angular --version angular --v angular -version angular -v Unfortunately, I received this error: -bash: angular: command not found Based on yeo ...

Leveraging the power of Google functionality in combination with Node.js, Express,

I've recently implemented the passport-twitter strategy, but I'm encountering an issue where I can't see the passport-login window on my client side when running the strategy. Here's a snippet of what I have initially: class Auth exte ...

Creating encoded objects for a content-type of `application/x-www-form-urlencoded`

Upgrading AngularJS Code to Angular 2+ - Http Issue I am in the process of converting some legacy AngularJS code (specifically Ionic 1) to the latest version of Angular (Ionic 4), and I've encountered a troubling issue. Previously, in every HTTP POS ...