Tips for showcasing information of a particular child in a database

I am currently immersed in a project that involves Cloud 9 and Ionic, with a Firebase database at its core. My main challenge lies in referencing the specific details of a particular vehicle (as per the database layout) and then displaying this information on a webpage.

{
  "userProfile" : {
    "fjN6auulwkguoB4SsUKyiKXZzNx1" : {
          "birthday" : "1997-06-12",
          "drivers" : {
              "-KqbyzU_KKYtpmewoDza" : "Test"
         },
          "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee848f9d8180ae9a8b9d9ac08d8183">[email protected]</a>",
          "licenseNum" : "1234",
          "name" : "Tester",
          "password" : "123456",
          "surname" : "Test",
          "vehicles" : {
              "-Kqbywf6e8VkojtLTUyi" : {
                 "location" : "Stellenbosch",
                 "make" : "Mercedes-Benz",
                  "mileage" : "123",
                  "model" : "SLK",
                  "year" : "2017"
             },
                 "-Kqc-yYdd5DKnodnAWe6" : {
                  "location" : "ste",
                 "make" : "BMW",
                  "mileage" : "123124",
                "model" : "dfg",
                "year" : "2016"
             }
        }

Essentially, each user has a unique key assigned by the database, containing attributes such as email and birthday. The objective is to identify the current logged-in user to access their unique key, followed by displaying all vehicles associated with that user. Clicking on a specific car should lead to a new page showcasing detailed information about the selected vehicle. I'm facing difficulties in referencing the vehicle key and passing those specifics to the respective page. The code snippet below from "client-profile.ts" allows me to display user details:

export class ClientProfilePage {
  private userPhotoUrl:any;
  private userDisplayEmail : any;
  private userDisplaysName : any;
  private userDisplayName : any;
  private userDisplayBirth : any;
  private userDisplayLicense : any;

  constructor(public navCtrl: NavController, private AuthProvider: AuthProvider) { 

    var myUserid= firebase.auth().currentUser.uid; //current user id
    this.displayUser(myUserid);

  }

  displayUser(theUserId){

    var that = this;

    this.AuthProvider.viewUser(theUserId).then(snapshot => {

       that.userDisplayEmail= snapshot.val().email;
       that.userDisplayName= snapshot.val().name;
       that.userDisplaysName= snapshot.val().surname;
       that.userDisplayBirth= snapshot.val().birthday;
       that.userDisplayLicense= snapshot.val().licenseNum
    })
}

The related code from "auth.ts" is provided below:

export class AuthProvider {

  public fireAuth:firebase.auth.Auth;
  public userProfileRef:firebase.database.Reference;  
  public userProfile:firebase.database.Reference;  

  constructor(public http: Http) {
    this.fireAuth = firebase.auth();
    this.userProfileRef = firebase.database().ref('/userProfile');   

  }



  loginUser(email: '', password: ''): firebase.Promise<any>{
    return this.fireAuth.signInWithEmailAndPassword(email, password);
  }

  viewUser(userId: any){
            var userRef = this.userProfileRef.child(userId);
            return userRef.once('value'); 
}

Any assistance or guidance would be greatly appreciated!

Answer №1

This solution will generate an array of vehicles within the userProfile property that can be utilized in your view.

In order to create a database reference, you will need the uid, which can be obtained by returning it from your AuthProvider:

let ref = firebase.database().ref('userProfile/' + uid);
const promise = new Promise((resolve, reject) => {
  ref.once('value') // Retrieve user profile
    .then((userProfile) => {
      ref.child('vehicles') // Get vehicles
        .once('value')
        .then((vehicles) => {
          var vehicleArray = [];
          vehicles.forEach(vehicle => { // Iterate through vehicles and add to array
            vehicleArray.push(vehicle);
          });
          var userProfileWithVehicles = userProfile.val(); 
          userProfileWithVehicles.vehicles = vehicleArray; // Incorporate array of vehicles into userProfile object
          resolve(userProfileWithVehicles);
        });
    });
});

promise.then(userProfile => {
  console.log(userProfile); // Object for view
});

While this method may appear more complex than your current setup, the nested structure is necessary to ensure all data is captured. If preferred, you can perform the above actions within your AuthProvider and return a promise to your ClientProfilePage instead of placing it directly in the view's code logic.

By leveraging the vehicle array, you can iterate through and pass relevant information to another 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 create a table in BigQuery, the operation may fail if the JSON key includes a

The data I have is in JSON format from a Firebase Backup. Every key in the data is preceded by a hyphen. Here is an example of the data: "-GuGCJDEprMKczAMDUj8":{"deviceId":"399a649c6cee6209","dow":"Thursday","downloadFlag":"N","event":"streamStart","half ...

What is the reason for the inability to import a router for express in TypeScript?

I have been working on setting up a basic Hello World REST service using NodeJS and Typescript. I attempted to organize the routers into separate files, but encountered some issues along the way. Specifically, when making a GET call to http://localhost:30 ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

What is the best way to asynchronously refresh Angular 2 (or 4) PrimeNg Charts?

Issue: How can PrimeNg Charts be updated asynchronously? Situation: I have a dropdown menu that should trigger a chart refresh based on the user's selection. I believed I had the solution figured out, understanding Angular change detection and reali ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

How can TypeScript associate enums with union types and determine the type of the returned object property?

I have a unique enum in conjunction with its corresponding union type. type User = { name: string, age: number } export enum StorageTypeNames { User = "user", Users = "referenceInfo", IsVisibleSearchPanel = "searchPane ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...

React throwing an error when trying to use inline fontWeight styling with Typescript

I am currently working on applying a CSS rule to a td element. const boldText = { fontWeight: 'bold' } <td style={boldText}>Content</td> Unfortunately, I am encountering the following error: [ts] Type '{ style: { fontWeig ...

Issue: The client assertion could not be signed due to the absence of client JWKs for Zitadel and OpenID Client integration

Currently leveraging Zitadel as my Identity Provider, I have set up a project and an API with a key. I am now in the process of acquiring a M2M token using the “JWT bearer token with private key” method, recommended by Zitadel (click here). Utilizing t ...

Tips for implementing Material-UI components in a .ts file

I am currently working on some .ts files for mocks, and I have a question about inserting MUI elements such as the Facebook icon. export const links: Link[] = [ { url: "https://uk-ua.facebook.com/", **icon: <Facebook fontSize ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

How can I add a new property to an object type within an Interface in TypeScript?

I'm currently exploring how to merge declare an interface, with the twist of adding a property to the object literal type instead of directly to the interface itself. Within a library, I have a type that looks like this: interface DefaultSession { ...

Updating the text area value based on the selected option in a dropdown using Typescript within Angular6

I'm currently facing an issue with updating the text area value based on the selection from a dropdown menu. Below is the design of the dialog: https://i.sstatic.net/67U1M.png Here's the code snippet I've incorporated for this functionalit ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Is it possible to export an imported merged namespace in Typescript?

Within my library, I have a collection of merged declarations setup like this: export class Foo {...} export namespace Foo { export class Bar {...} ... } export default Foo These merged declarations often contain inner classes and specific errors r ...

Strategies for retaining a list of chosen localStorage values in Angular6 even after a page refresh

When I choose an option from a list of localStorage data and then refresh the page, the selected data disappears. selectedColumns: any[] = []; this.listData = [ { field: "id", header: "Id", type: "number", value: "id", width: "100px" }, { field: "desc ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

What is the best way to share a configuration value retrieved from the back end across all components of an Angular 6 application?

In the Web API's Web.config file, I have defined configurations like MAX_FILE_SIZE and others. I want to retrieve these configurations from the backend and make them available to all Angular 6 components globally. Could someone suggest the most effect ...