Can this function be rewritten in a manner that does not involve returning undefined?

Using angular fire, I am fetching data from firestore based on the logged-in user. After ensuring that the user object has been retrieved, I have a command to monitor changes in the document.

async fetchUserCards() {
  let _user: UserModel = await this.authService.retrieveUser();

  if (_user) {
    return this.angularFirestore
      .collection<Card>('cards', (ref) =>
        ref.where('owner', '==', _user?.uid)
      )
      .valueChanges();
  } else {
  }
}

As there is an If check for the user, the function's signature becomes Promise<Observable<board[]> | undefined>. How can I eliminate the need for 'undefined' (what should I do in the else block)?

Answer №1

To make your code more concise, you can streamline it to return the Observable<Board[]> directly instead of returning a Promise. Here is how you can achieve that:

// import { from, Observable } from 'rxjs';
// import { filter, mergeMap } from 'rxjs/operators';

getUsersCards(): Observable<Board[]> {
  // If `this.authService.GetUser()` returns an Observable, you can use it without the need for the `from` function.
  // The `from` function is typically used to convert Promises into Observables.
  return from(this.authService.GetUser()).pipe(
    filter((user) => !!user),
    mergeMap((user) =>
      this.angularFirestore
        .collection<Card>('cards', (ref) =>
          ref.where('owner', '==', user?.uid)
        )
        .valueChanges()
    )
  );
}

You can then utilize this function in your component or service as shown below:

getUsersCards().subscribe((res: Board[]) => console.log(res));

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

Angular 9 introduces a new feature where canActivate now supports Observable<boolean> which provides a more robust error handling mechanism for failed

Currently, I am working with angular9 and rxjs6 while implementing canActivate: Observable feature. However, I encountered an error when attempting to use catchError, as shown in the image below: https://i.sstatic.net/Q0Xuu.png Is there a solution to fix ...

Exploring nested JSON responses in Angular 2 with TypeScript

Below is the JSON response I received from the REST endpoint: {"image_2_11_0-51-upgrade.iso": {"model": "somemodel", "hostnames": ["abc.com", "abcd,com"], "upload_status": false, "version": "2.11.0-51"}, "image_2_11_0-51-upgrade.iso": {"model": "newmo ...

The error message "Property 'DecalGeometry' is not found in the type 'typeof "..node_modules/@types/three/index"'."

Within my Angular6 application, I am utilizing 'three.js' and 'three-decal-geometry'. Here is a snippet of the necessary imports: import * as THREE from 'three'; import * as OBJLoader from 'three-obj-loader'; import ...

Unexpected termination during the npm installation process without providing a clear error message

Every time I try to create a new Angular2 app using the command ng new new-app, angular-cli successfully generates the necessary files and then proceeds to run npm install. However, the npm install process abruptly stops with no error message provided. As ...

Upgrade your buttons with dropdowns from Bootsrap to ng-bootstrap for a fresh new look

Hello, I am new to Angular and I need help creating code for the ng-bootstrap. I am familiar with bootstrap-4 but not so much with Angular. I have tried following the Ng-bootstrap drop-down example from their website but it is not working for me. Can som ...

Angular2/4 preflight request encountered an invalid response which resulted in a redirect

In my project, I am utilizing angular4 for the frontend and a spring boot application for the backend. The communication between the frontend and BFF (backend for frontend) is done via RESTful requests. When the frontend sends a POST request to the backen ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Enhance typescript interfaces with third-party library components in React.js

As a newcomer to typescript, I am in the process of converting my existing react project to use typescript. After changing my files to tsx, I encountered several errors which I managed to resolve except for one type-related issue that I couldn't find ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Ionic's ion-back-button is only navigating back to the defaultHref

I'm encountering a problem with the ion-back-button in Ionic v5 with Capacitor and Angular. My goal is to have Tab1 contain a button that navigates to Tab2. Tab2 should have an ion-back-button in its tool-bar that will navigate back to the previou ...

Issue with rejecting a promise within a callback function in Ionic 3

Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their locati ...

Interacting with backend APIs using Angular 2

Currently, I am working on an Ionic AWS application and have completed the front-end development phase. Here is what I have so far: Front-end repository: Ionic front-end List of Backend repositories: Example resources Example get Example post ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Using NextJS: Issue with updating Value in useState

In my current project, I am attempting to display a string that changes when a button is pressed in my NextJs application. Here's the code snippet I am working with: 'use client' import { useState } from 'react' export default fu ...

What is the best way to address this conflicting Angular node package module dependency?

Recently, I completed updating all my node modules through the npm-check-updates tool. This was necessary to be able to install the latest version of ngx-stripe from https://ngx-stripe.dev/, as it required some newer versions of node modules that were miss ...

Is there a way to use router.navigate conditionally when navigating?

I am currently dealing with a scenario where I have a table of entities. Upon clicking a row, the user is directed to another page which represents the entity (view page). The implementation utilizes router.navigate. The issue arises when an entity is del ...

Error TS2351: You cannot utilize the 'new' keyword with an expression that does not have a call or construct signature

I'm facing a little difficulty with implementing cropperjs in my project. Despite my efforts, I keep encountering the error mentioned above. Could you please take a look at my code? module view.pages.controllers { export class CropToolController { ...