What steps can be taken to address Promise discrepancies in an Angular/Typescript application?

I have been working on retrieving a User object from Firestore within my Angular application.

The User model looks like this:

import { PlaceLocation } from './location.model';

    export class User {
        constructor(
            public userId: string,
            public userName: string,
            public isMechanic: boolean,
            public location: PlaceLocation
        ) { }
    }

In the component, I have the following code snippet:

user: User;

this.usersService
    .getUserByUserId(paramMap.get('id'))
    .subscribe(user => {
        this.user = user;
});

This is the method in the Users Service used to retrieve the user:

getUserByUserId(userId: string) {
    return of(
      firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
        .then((querySnapshot) => {
          console.log("Query Snapshot:", querySnapshot);
        }).catch((err) => {
          console.log("Query Error:", err);
        })
    );
  }

However, when I try to assign this.user = user, I encounter the following compilation error:

Type 'Promise' is missing the following properties from type 'User': userId, userName, isMechanic, location

I would appreciate some guidance on what changes need to be made to address this issue. Thank you!

Answer №1

If you're dealing with an observable of a promise, consider using from instead. This function converts a promise into an observable.

  fetchUserById(userId: string) {
    return from(
      firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
    ).pipe(
      map(querySnapshot => { ... perform necessary transformations ... }),
      tap( // handle errors and log in observable style
        query => console.log(query, 'success),
        error => console.log(error, 'error')
      ),
      // catchError(error => { ... handle the error ... })
    );
  }

Answer №2

Using the "from(...promise...)" solution may not always be reliable as the promise could resolve before you subscribe to it.

The correct approach is to create an observable from the beginning:

getUserByUserId(userId: string) {
  return new Observable<any>((observer: Observer<any>) => {
    firebase.firestore().collection("users").where("userId", "==", userId)
        .get()
        .then((querySnapshot) => {
          observer.next(querySnapshot);
          observer.complete();
        }).catch((err) => {
          observer.error(err);
        })

  });
}

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

Combining two arrays in typescript using the map method

I have an array of heart rate, height, and weight values. { "heart_rate": 27, "height": 82, "weight": 78 } There is also a second array containing information about each value, such as ID, label, and description. ...

Tips for effectively navigating through pages using routing in angular 4?

'navigation.ts' File import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; //Layouts import { MainLayoutComponent } from './layouts/main-layout.component'; //pages imp ...

The element called 'userForm' cannot be found within the 'RootComponent' instance

My Angular component class is facing a strange issue when I try to compile it using npm start. The first time, it fails to compile and throws the error: ERROR in src/app/root/root.component.ts(14,12): error TS2339: Property 'userForm' does not e ...

Utilizing properties in a fresh function with Angular 2

Having an issue with the beacon Minor propriety in a new function. The editor keeps saying that the name cannot be found, and I'm not sure how to resolve it. Function Example: listenToBeaconEvents() { this.events.subscribe('didRangeBeacons ...

Angular todo app adds functionality to update array counts based on object properties

Hey there! I'm working on a todos app with CRUD functionality in Angular to get the hang of Angular 6. At the bottom, there's a link that shows how many todos are left to complete. Right now, this counter updates every time I add or remove a to ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

In Typescript, issues arise when trying to assign types with inheritance in Generics - Type mismatch detected

As I work on creating a generic parent class to handle multiple children, I have encountered a challenge. My goal is to define an abstract function in the parent class that will take in a child object and return that same class. Here's my initial atte ...

The Typescript "and" operator is used for combining multiple conditions

I'm having difficulty understanding the functionality of the & operator in TypeScript. I recently encountered this code snippet: type IRecord<T> = T & TypedMap<T>; Can someone explain what this operator does and how it differs fr ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Leverage and implement personalized variables within an Angular toolbox

I have created an Angular library that includes a component called myComponent. The library builds successfully and can be used in my main application. I'm looking to enhance the functionality by allowing the main application to customize certain scss ...

Facing a deployment problem on Firebase while attempting to deploy a Node.js application that was developed in typescript instead of javascript, using the "firebase serve" command

Attempting to host a nodejs API on Google Cloud, specifically Firebase, but encountering the following error. Here are the steps I've taken: Ran tsc src\index inside functions folder to compile typescript file. Tried "firebase serve" (Error 1) ...

Dynamic Rendering and Retrieving Component HTML in Angular

Generate the HTML code of a component to open a new tab with an about:blank page. Reason: This method helps avoid creating HTML using string variables, such as: var html = '<div> <h3>My Template</h3> &a ...

In TypeScript, the 'onChange' is declared multiple times, therefore this particular usage will be scrutinized carefully

Within my React project, I am utilizing material-ui, react-hook-form, and Typescript. However, I encountered an error in VSCode when attempting to add the onChange function to a TextField component: 'onChange' is specified more than once, resul ...

What is the best way to locate an item within a Redux array when working with TypeScript?

Below is the content of my slice.ts file. interface iItem { Category: string; Id: string; } interface iDataState { Items: Array<iItem>; } const initialState: iDataState = { Items: [], }; reducers: { updateItem: (state, action: PayloadAc ...

Struggling to retrieve a route parameter using route.snapshot within the main component

How can I retrieve a token from the URL? Currently, it is returning null as a value. In my app.component.ts file: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ sel ...

Encountering a CORS policy issue while attempting to remove an entry using Spring framework

Within my Spring Application, there is a controller file that looks like this: @RestController @CrossOrigin(origins = "*", allowedHeaders="*") @RequestMapping("/mxkLicenseGenerator") public class MXKLicenseController { @A ...

angular 4+ dynamically assign @Input for components created using ngComponentOutlet

If you are using Angular 4 and need to dynamically generate a component, you can utilize the ngComponentOutlet directive. Here is a reference link for more information: https://angular.io/docs/ts/latest/api/common/index/NgComponentOutlet-directive.html Fo ...

Using Angular CLI to create a new project with SASS from an existing project

After diving into a project generated by Angular CLI, I realized I forgot to include the --style=sass flag. Is there a method to transition my project to support SASS using Angular CLI? ...

Angular 2 and ASP.NET MVC combined application without using Single Page Application techniques

Back in my Angular 1 days, I used to define my app within the body tag like this: <body ng-app="myapp">. This allowed me to load different controllers for various views within my MVC application. For example, I could load one controller in the Home/ ...

Why is the observable I'm utilizing in this Angular 11 component returning as undefined?

Currently, I am working on implementing a promotions feature for an Angular 11 e-commerce application. I have developed a service that sends a get request and retrieves a JSON file containing the campaign's information. The Service: import { Injectab ...