Mapping Firestore data to TypeScript interface in Ionic/Angular application: A comprehensive guide

Here are a few documents I am fetching from firestore:

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

This is the method I'm currently using:

private _mechanics = new BehaviorSubject<User[]>([]);

fetchMechanics() {

    return of(
      firebase.firestore().collection("users").where("isMechanic", "==", false)
        .get()
        .then((docs) => {
          const data = []
          docs.forEach((doc) => {
            data.push(doc);
          });
          console.log('Service Data:', data);
          this._mechanics.next(data)
        }).catch((err) => {
          console.log(err);
        })
    );

  }

Now, I aim to transform the data to comply with my UserData interface:

interface UserData {
  userId: string,
  userName: string,
  isMechanic: boolean,
  location: PlaceLocation
}

Could someone kindly advise on what modifications I should make to fetchMechanics() for this purpose?

Here's an illustration of the data in firestore:

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

In addition, I've been attempting to replicate the following code, but have not succeeded thus far:

private _users = new BehaviorSubject<User[]>([]);

fetchUsers() {
    return this.http
      .get<{ [key: string]: UserData }>('firebaseUrl/users.json')
      .pipe(map(resData => {
        const users = [];
        for (const key in resData) {
          if (resData.hasOwnProperty(key)) {
            users.push(
              new User(
                key,
                resData[key].userName,
                resData[key].isMechanic,
                resData[key].location)
            );
          }
        }
        return users;
      }),
        tap(users => {
          this._users.next(users);
        })
      );
  }

Answer №1

If the data in a collection has the same structure as an interface, you can simply cast the object to the interface like this:

interface PersonData {
  personId: string,
  fullName: string,
  isStudent: boolean,
  location: PersonLocation
}

private _people = new BehaviorSubject<PersonData[]>([]);

constructor(private firestore: AngularFirestore) {
}

fetchPeople() {

  return this.firestore
    .collection("persons")
    .ref
    .where("isStudent", "==", false)
    .get().then((querySnapshot) => {
        const data: PersonData[] = [];
        querySnapshot.forEach((doc) => {
            data.push(doc.data() as PersonData);
            console.log(doc.id, " => ", doc.data());
        });
        this._people.next(data)
    });

}

Answer №2

Here is the solution I came up with:

getLocation(){

 const db = this.fire.firestore;
 db.collection("trains").get().then((result)=>{
   console.log(result.docs.map(train=>train.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

What is the process for including a dependency in an npm package in order to install another npm package?

As I work on creating an npm package for my Angular app, I find myself in need of including a dependency that already exists on npm. My dependency object will include the following entries: "dependencies": { "@angular/animations": "^6.1.0", "@angu ...

Updating the src attribute within a modal using Angular

Struggling for days to update the src attribute with no success. Any assistance would be greatly valued. Here's the HTML: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleM ...

When there are updates in language, a new service request is needed

I'm currently working on a component that I navigate to, which means it doesn't have a parent or child. The language in this component is changed using the TranslateService, and this service is called from my app.component, which acts as the base ...

In JavaScript or TypeScript, you can calculate the number of duplicate objects in an array by adding an "amount" property to each item

Currently, I have an array of items that contains duplicates. My goal is to count the duplicates and update one item with the total count while discarding the other duplicate. Here is my initial data: (simplified) [ { "id": "fishing_r ...

Update information in a component without having to refresh it when navigating to a different route

I am currently facing a challenge with my components B and A. Component B has a post method that inserts new data and navigates directly to component A, which has a get method to display the inserted data. My issue is how to retrieve the new data without ...

How can you automate the process of skipping a protractor test?

Is there a way to skip protractor test cases based on certain conditions being true or false? I tried using pending('skipped'); expect(true).toBe(true); But it is marked as failed. Update I found a way to add test cases to "Pen ...

Having trouble with running Ionic serve in your Ionic 2 project?

While running the command `ionic serve` in node.js command line or GitHub power shell, I encountered the following error: There is an error in your gulpfile: Error: `libsass` bindings not found. Try reinstalling `node-sass`? at getBinding (D:\Git ...

What is the most effective method for transitioning between states in Angular when it comes to modifying the HTML display?

When faced with the decision of choosing between two different approaches for managing component view during loading, the "best way" refers to performance and minimizing UI blinking (reducing DOM renderizations). Approach 1: Utilize a loading variable to ...

What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account. Below is the error message in the browser console: page.tsx:14 POST http://localhost:3000/api/auth/ ...

Is there a way to verify within the "if" statement without repeating the code?

Is there a way in javascript (or typescript) to prevent redundant object rewriting within an if statement condition? For example: if (A != null || A != B) { // do something here } // can it be done like this: if (A != null || != B) { // avoid repeating ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Ways to integrate object-or-array with recursion in Typescript

I am striving to achieve the following: type Foo = ({bar: string} & Record<string, Foo>) | Foo[] However, I keep encountering issues such as circular references in type or the constraint that An interface can only extend an object type or inte ...

Removing redundant names from an array using Typescript

My task involves retrieving a list of names from an API, but there are many duplicates that need to be filtered out. However, when I attempt to execute the removeDuplicateNames function, it simply returns an empty array. const axios = require('axios&a ...

Custom fields provided by Express are not accessible within routes

In my customExpress.d.ts file, I have defined an extended type: declare namespace Express { export interface Request { user: { id: string; }; } } I have also configured it in the tsconfig.json file: ... "typeRoots": ["sr ...

Leveraging Angular2 for Azure AD authentication

Currently working with Angular2 and looking to authenticate users through Azure AD. I came across ADALjs, but it's specifically for Angular1. I also found this https://www.npmjs.com/package/angular2-adal#adalService, however it appears to still be in ...

Passing properties by reference in Typescript allows for the direct manipulation

In my Typescript class, I have four properties defined like so: class MyClass { private x: number; private y: number; private z: number; private w: number; } I am looking to create individual functions that will increment each of thes ...

Can the sequence of file executions be stored in a node/express application?

Is there a way to track the order in which files are executed when running the program and display them in the console like so? npm run dev ... -> 1. src/index.ts -> 2. src/model/something.ts -> 3. src/lib/something.ts -> ... I could manua ...

Implementing a Loading Spinner with Angular4's HttpClient Interceptor

Within this code snippet, you will find the interceptor I created to manage the spinner directly through the interceptor itself. @Injectable() export class ApiInterceptor implements HttpInterceptor { constructor(private _globalSpinnerService: GlobalSp ...

Setting a default value for a textfield within Angular 4

Within my for loop, I am displaying the name and price of a selected product. Users can input a quantity, with the default being 1. How can I set the text field value to default to 1? I've attempted the following method but it doesn't seem to be ...

Guide on integrating an Angular 10 Component into a cell in Ag-Grid

I am currently working with an Angular10 component, specifically a toggle switch, that I need to integrate into a specific column within my ag-grid cell. Currently, I am using a basic HTML checkbox in the following manner: colDefs: ColDef[] = [ { fiel ...