When you refresh the page, the collection is not retrieved - AngularFire

Whenever I refresh the page, my constructor call doesn't initialize properly.

I've been following this guide:

https://www.youtube.com/watch?v=gUmItHaVL2w&ab_channel=TraversyMedia
https://github.com/angular/angularfire

UPDATE:

In order to make it work again, I have to navigate to another page, refresh, and then go back for the call to be executed correctly.

schedule.service.ts

import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {ScheduleInterface} from '../../models/schedule';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {AuthService} from '../auth/auth.service';


@Injectable({
  providedIn: 'root'
})
export class ScheduleService {
  schedulesCollection: AngularFirestoreCollection<ScheduleInterface>;
  schedules: Observable<ScheduleInterface[]>;
  scheduleDoc: AngularFirestoreDocument<ScheduleInterface>;

  constructor(private afs: AngularFirestore, private authService: AuthService) {
    console.log('scheduleService called1');
    this.schedulesCollection = this.afs.collection('schedules', ref => ref
      .where('UID', '==', this.authService.currentUserId)
      .orderBy('user', 'asc'));
    console.log('scheduleService called2');
    this.schedules = this.schedulesCollection.snapshotChanges()
      .pipe(map(changes => {
        console.log('scheduleService called3');
        return changes.map(a => {
          // not triggered on page refresh
          console.log('scheduleService called4');
          const data = a.payload.doc.data() as ScheduleInterface;
          data.docRef = a.payload.doc.id;
          return data;
        });
      }));
  }

  getSchedules() {
    return this.schedules;
  }

Console

https://i.sstatic.net/NgIed.png

Answer №1

To properly retrieve data from the observable, it is important not to subscribe directly in the constructor. Instead, create a method that returns an observable and move the logic there.

   fetchData(): Observable<DataInterface> {
        return this.db
            .collection("data", (ref) =>
                ref
                    .where("userID", "==", this.authService.getCurrentUser())
                    .orderBy("date", "asc")
            )
            .snapshotChanges()
            .pipe(
                map((changes) => 
                    changes.map((a) => {
                        const info = a.payload.doc.data() as DataInterface;
                        info.refID = a.payload.doc.id;
                        return info;
                    })
                )
            );
    }

In your component where you want to access this data, inject the service and call the fetchData method from there.

export class YourComponent implements OnInit {

        constructor(protected dataService: DataService){}

        ngOnInit(): void {
            this.dataService.fetchData().subscribe(response => {
                console.log(response);
            });
        }
    }

Answer №2

It seems like you might be fetching the initial value when schedules hasn't been defined yet. To resolve this issue, consider implementing the following:

get mySchedules() { return this.schedules }

Alternatively, refrain from invoking the method and simply access scheduleService.schedules.

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

Should Angular 2 components be required in a top-down or bottom-up approach?

As I dive deeper into Angular 2 and explore its components, a lingering question has been on my mind. My main concern with Angular 1 lies in the top-down require pattern used in directives/components. It feels counterintuitive for components to rely on oth ...

NodeJS and Angular2 application experiencing loading issues

Currently, I am diving into the world of Angular2 and thanks to the quick start guide provided on their official documentation, I have successfully set everything up. However, if I plan to work with APIs on the server or host my project in the cloud, it ap ...

Issue TS1192: The module named "A.module" does not contain a default export

After creating a new module 'A', I attempted to import it in another module named 'B'. However, during compilation, I encountered the following error: Error TS1192: Module '" A.module"' has no default export I wou ...

Troubleshooting Errors in Angular CLI's ng test Command

After installing TypeScript 2.1 and the latest Angular CLI, I encountered an issue where ng test gives an error while ng e2e runs smoothly. <--- Last few GCs ---> 52499 ms: Mark-sweep 1366.6 (1434.2) -> 1366.6 (1434.2) MB, 1045.6 / 0 ms [allo ...

npm is asking for a peer to be installed, but none was found

I am facing some warnings that I can't seem to resolve. Despite my attempts at installing the required dependencies, I have not been successful. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0f041843050b171901 ...

Encountering an issue while trying to integrate custom commands using the addCommand function in WebDriverIO

When using the addCommand function to add a new command, I encountered an error message that states: [ts] Property 'WaitForElementsAmount' does not exist on type 'Client<void>'. Here is an example of the code snippet I used: br ...

Oops! An error occurred: Uncaught promise in TypeError - Unable to map property 'map' as it is undefined

Encountering an error specifically when attempting to return a value from the catch block. Wondering if there is a mistake in the approach. Why is it not possible to return an observable from catch? .ts getMyTopic() { return this.topicSer.getMyTopi ...

The traditional Angular model definition has been revamped with the implementation of web services model

I have a TypeScript model that looks like this: import * as moment from 'moment'; export class Activity { public id: number; public activityDate: string; public day: number = moment(this.activityDate).dayOfYear(); } Also, a C ...

Troubleshooting change detection problem in Ionic 3 application

There seems to be an issue with the data not being reflected in the view despite changes in the service and component. Various solutions were attempted to address this issue, but none have proven successful: Utilized the ngDoCheck lifecycle hook Imp ...

What is the method for retrieving the compilation list of Typescript files that tsc will process?

In my Typescript project, I am currently working on creating a grunt task to gather statistics from the source files. I have a function that takes one source file at a time, runs typescript.createSourceFile on it, and performs some actions on the resulting ...

The Angular 6 ngb-bootstrap modal fails to display due to conflicting bootstrap css within a div element

I've encountered numerous inquiries about modal not displaying, and although I've successfully implemented it in other scenarios, this one presents a unique challenge! In my Wordpress project, I've embedded an Angular app within the admin a ...

Create a distinct timer for every item in the ngFor loop

Utilizing angular, a custom stopwatch has been created. The challenge lies in managing unique timers for each ngFor item despite having start/end buttons for each item. https://i.sstatic.net/c4oM8.png In the provided image, distinct start/end buttons are ...

How can you ensure only one mat-accordion and nested mat-expansion-panel is open at a time?

The current setup includes the following structure: <mat-accordion> <mat-expansion-panel>(some panel body)</mat-expansion-panel> <some-component></some-component> </mat-accordion> Furthermore, the template of some- ...

Creating an NPM package that utilizes global types without altering the project it is integrated with

The Dilemma: When working on a project that involves reusing multiple types across various files, utilizing types defined in a script file can be advantageous. These global types are accessible throughout the entire project without the need for importing, ...

The themes from Infragistics are not functioning as anticipated. The default theme is not being applied properly

Initially, I was hopeful that by writing a few lines of code, I could incorporate one of the Infragitics themes from their guide. () My focus was on the "Default Theme" portion. After setting up a new Angular project with the Infragistics angular-cli, I a ...

Compose Standard Text for Native-Base Input

When calling a component, I pass a string like this: <TripsPage startingPoint={startingPoint} /> Within this component, there is a label: <Item fixedLabel> <Input/> </Item> Upon open ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

What is the best way to accept user input in typescript?

Currently, I am working on a TypeScript project that involves taking user input for the addition of two numbers. Below is the code snippet I am using: function rotatedString(S1,S2){ return S1+S2; } function processData() { //INPUT[uncomment & m ...

How might one utilize the latest Angular control flow syntax to conditionally enclose a <span> with an <a> tag

I am seeking a solution to conditionally wrap a span with an anchor tag to create a link. There are multiple approaches to accomplish this, but I am curious if there is an optimal method. Here is the desired outcome: If the item has a URL, the HTML should ...