Tips for retrieving a single record from Firebase using Angular 2

I am struggling to retrieve a single record by uid from my Firebase database in an Angular 2 app. The issue I am facing is that the profile variable always returns as undefined. Can someone guide me on the correct approach to solving this? Thank you! My code:

Profile class

export class Profile{
   constructor(public $key:string, public userId:string, public description:string, public avatarUrl: string){
   }

    static parseFromJson({$key, userId, description, avatarUrl}):Profile{
        return new Profile($key, userId, description, avatarUrl);
    }
}

Profiles service

@Injectable()
export class ProfilesService {
  constructor(private db: AngularFireDatabase) {
  }

  getUserByUserId(userId:string): Observable<Profile>{
    return this.db.list('profiles',{
        query: {
          orderByChild: 'userId',
          equalTo: userId
      }
    }).map(result => Profile.parseFromJson(result[0]));
  }
}

Profile component

export class ProfileComponent {

  profile: Profile;
  uid: string;

  constructor(private profileService: ProfilesService, private af: AngularFire) {
    this.af.auth.subscribe(auth => this.uid = auth.uid);
    this.profileService.getUserByUserId(this.uid).subscribe(
        result => {
          this.profile = result;
        }
     );
   }
}

Answer №1

After performing some operations, an array is obtained which can be further processed by extracting the first value and converting it to type Observable.

The method .first will only emit the initial value from the source Observable.

 fetchUserByID(userID:string): Observable<Profile>{
    return this.db.list('profiles',{
        query: {
          orderByChild: 'userID',
          equalTo: userID
      }
    })
    .first()
    .map(response => Profile.parseFromJson(response));

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

SecretKey is not valid, FirebaseError code: 400

Currently, my backend is powered by Firebase. However, when I initiate it using NODE_ENV=debug firebase emulators:start --inspect-functions, the following messages are displayed: emulators: Starting emulators: auth, functions, storage ⚠ functions: Ru ...

Tips for receiving a reply from a post request

After successfully making and completing a post request, I'm wondering about using console.log(res.valor) in the code to display the data: consultarCorreio(){ this.cartS.cart.valorTotalItems this.cartS.getCorreiosPrazoPreco(this.cartS.cart.pesoTot ...

Looking to execute multiple programs simultaneously within the prestart script in the package.json file, and bypass any exit error codes

I need to run yarn tsc and yarn lint during every yarn start to identify any code errors. This is how my scripts property is set up: "scripts": { "start": "expo start", "android": "expo start --android" ...

How do I create a generic function in TypeScript that adjusts its behavior based on the input argument?

Is there a way to create a generic function that can accept generic arguments like Data<string, number>? Take a look at this code snippet: interface Data<T,R> { a:T; c:R; } function foo( data: Data<string, number> ){ return t ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. https://i.sstatic.net/CZTO2.png The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it s ...

How can one determine the data type by analyzing the key value?

I'm attempting to determine the return type of getAllRaces() as () => Race[]. Here is what I have tried so far: type CollectionMap = { races: Race[] horses: Horse[] } type Race = { date: Date } type Horse = { name: string } typ ...

"Struggling to Get Angular2 HttpClient to Properly Map to Interface

Currently, I am integrating Angular with an ASP.NET WebApi. My goal is to transmit an object from the API to Angular and associate it with an interface that I have defined in Typescript. Let me show you my TypeScript interface: export interface IUser { ...

Variables for React/Firebase authentication being transmitted through the URL

While developing a web application with React and utilizing Firebase for authentication/database functionalities, I came across an issue in my browser history where the URL displayed the username and password in plain text (http://localhost:3000/login?emai ...

Universal - Permissible data types for function and constructor arguments

In many statically typed languages, it is common to specify a single type for a function or constructor parameter. For example: function greet(name: string) { ... } greet("Alice") // works greet(42) // error TypeScript is an extension of JavaScri ...

Update the Firestore data by modifying one value depending on another value, and then synchronize the user interface to display the updated information

Greetings! I'm a newbie to the world of Swift and have been diligently following tutorials to enhance my skills. Recently, I decided to take the plunge and build my own app. However, I've hit a roadblock and am struggling to find a solution. I wo ...

Enhancing the internal styling of ngx-charts

While working on the ngx-charts Advanced Pie Chart example, I noticed that the numbers in my legend were getting cut off. Upon inspecting the CSS, I discovered that a margin-top of -6px was causing this issue: https://i.stack.imgur.com/oSho1.png After so ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...

Utilizing momentjs to convert date and time to various time zones

Within my Angular application, there is a selectbox that allows users to choose the timezone for converting a specific time. I am currently utilizing momentjs for date-time manipulations, however, I am facing an issue regarding changing the timezone of the ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

Do you have any suggestions for optimizing an Angular 15 reactive form that gets filled with data from an API?

Creating an Angular 15 Reactive Form with FormGroup As I delve into the documentation to construct a form with 4 inputs that are populated with data retrieved via GET requests and then updated upon submission through PUT requests, I find that it is functi ...

What causes Angular projects to only display a single object when using an array?

I've been exploring the League of Legends API, specifically focusing on the champion json data it provides. Currently, I have developed a service using Angular: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders} f ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Ensuring min and max values are met using Mongoose for validation

I am currently developing a web application using the MEAN stack with Angular 6. I am working on implementing functionality to find and save 'eValue's within a certain range. The minimum value allowed is 0 and the maximum value is 1000. In my sch ...