Unable to retrieve information from a Firestore collection in Angular

Currently, I'm developing an Angular project that is connected to a Firestore database. In summary, the pages are stored in the database, and I have created a PageComponent that displays a URL like this: page/'id' and showcases the corresponding page based on the linked id. Despite using functions from a service that work on other components, I am facing an issue where I can only retrieve the page's id.

Below is my TypeScript code:

export class PageComponent implements OnInit {
  auth = this.admin.auth;
  id: string = '';
  page: Page = {
    id: '',
    titre: '',
    contenu: '',
  };
  constructor(
    private pagesservice: PagesService,
    private route: ActivatedRoute,
    private admin: AdminLoginService
  ) {}

  ngOnInit(): void {
    this.id = this.route.snapshot.paramMap.get('id') as string;
    if (this.id) {
      this.pagesservice.getPage(this.id).subscribe((p) => {
        this.page = p;
      });
    }
    console.log(this.id);
    console.log(this.page);
  }
}


And here is the service implementation:

export class PagesService {
  // Service methods for CRUD operations
}

Upon logging the output of ngOninit, here's what I get:

// console.log(this.id)
b 

// console.log(this.page)
Object { id: "", titre: "", contenu: "" }
​
contenu: ""
​
id: ""
​
titre: ""

The problem seems to revolve around the specific component - admin edit :

export class PagesFormComponent implements OnInit {
  // Implementation details for admin functionality
}

Finally, here is a snippet of the HTML template used:

<div class="container-fluid p-5">
    <form #pageForm="ngForm">
        <!-- Form elements -->
    </form>
</div>

The service functions correctly for other components, fetching data to populate an editing form. I need assistance in identifying the mistake that I might be making.

Answer №1

Take caution of the following:


 if (this.id) {
      this.pagesservice.getPage(this.id)
      .subscribe((p) => {
        this.page = p; // <==== Data will be available in 'this.page' only after this point        
        console.log(this.page);// <=== This log will display the data correctly
      });
    }
    console.log(this.id);
    // console.log(this.page); // At this point, 'this.page' is still empty.

The reason for this behavior is due to the asynchronous nature of the 'getPage' method. The data is retrieved inside the subscribe function when a response is received. However, the execution thread does not pause at the '.subscribe', causing the code to reach the last instruction (console.log(this.page);) before the data is available in this.page.

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

When attempting to send the token to the server using Angular's WWW-Authenticate: Bearer method, only to encounter a 401

I am a novice in Angular and I have developed a small role-based application using Angular 9 for the frontend and Asp.net core. Everything works fine when I log in or out of the app, and I can access non-Authorize controllers from the frontend without any ...

NestJS endpoint throwing a 500 error after submitting a post request

Struggling with sending post requests in NestJS as they are returning an error message: ERROR: An error occurred in POST /api/fraud-rules in 8ms... { "isError": true, "status": 500, "name": "InternalError", & ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

Due to a TypeScript error stating that the type '{ Id: number; Name: string; }' cannot be utilized as an index type, I am unable to assign a value for students at this time

I am facing an issue with defining a value for students in TypeScript. It is giving me an error saying that it can't be used as index type. Just to clarify, I have declared id as number (not Number) and Name as string (not String). import { Component ...

Error encountered when attempting to add document to Firebase database: admin:1. An unexpected FirebaseError occurred, stating that the expected type was 'Na', but it was actually a custom object

I am encountering an error when trying to add a document to my collection in Firebase. I have successfully uploaded an image to Storage and obtained the URL, but this specific step is causing issues. I have followed the code implementation similar to how F ...

Is there a way to disable editing functionality in CKEditor?

How can the ckeditor be made non-editable using a parameter? Below is an example code snippet showcasing the component in action. This is implemented in an Angular environment. <ckeditor [(ngModel)]="salesCondition.DeliveryTimeHtmlFormatted" [n ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

Developing a Typescript "Map" type using numerical enumerations

In my Typescript project, I came across the need to create record types with numeric enums: enum AxisLabel { X = 0, Y = 1 } export const labelLookup: Record<AxisLabel, string> = { [AxisLabel.X]: "X axis", [AxisLabel.Y]: "Y Axis" }; However, I w ...

Setting up in the namespace for typescript

Is there a way to assign to namespaces using dot notation like this? namespace item {} item.item1 = { name: "Some Item" } item.item2 = { name: "Some Item" } An error is thrown with: Property 'item1' does not exist on ty ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

Interface constructor concept

Trying to figure out how to dynamically add different types of components to a game object in TypeScript. After consulting the TypeScript documentation on interfaces, I discovered a unique approach for dealing with constructors in interfaces, which led me ...

Ways to resolve the issue of missing data display in Angular when working with the nz-table

Below is the code snippet: <nz-table #listTable nzSize="middle" [nzData]="data"> <thead> <tr> <th nzShowExpand></th> <th>Location</th> <th>Device</th> ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

Strategies for excluding a union type based on the value of a field

I have this specific type structure (derived from a third-party library): type StackActionType = { type: 'REPLACE'; payload: { name: string; key?: string | undefined; params?: object; }; source?: string; ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

Invoking a parent component's function using jQuery summernote

I'm having trouble calling a function from outside of a custom button component that I am adding to the ngx-summernote toolbar. The code I currently have is causing compilation errors. I've tried various methods, but they all result in an error s ...

Tips for creating a table in Angular 2

I need help creating a new row in a table using Angular. I know how to do it in pure Javascript, like the code below where addRow() method is called to generate a new row. But I'm new to Angular and want to learn the correct way to achieve this withou ...

How can I exclude TypeScript files generated from js in WebStorm?

Using the Enable Typescript Compiler option results in a .js file being generated for every .ts and .tsx file by the TypeScript compiler. https://i.sstatic.net/Yr0lR.jpg When performing code completion, WebStorm does not recognize that the files were aut ...

Limit access to a menu following authentication

Within the sidebar section, there are 4 rubrics available (Administration, Marché, Portefeuille, Déconnexion). https://i.sstatic.net/O8zpH.png Upon user authentication, I want the Portefeuille rubric to remain hidden. To achieve this, I have implement ...