What is the best way to perform a conditional check and return a customized object while working with a Promise?

I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means I need to handle this at the page level as shown below:

ngOnInit() {         
    this.dbcon.getUser().then(dbvalue=>{
      if(dbvalue.val()){
     //..do something.. 
     }      
    }); 

Instead of returning null, I would prefer the provider to return a valid object or something like {sorcode:''}. Any suggestions on achieving this at the provider level are appreciated.

When I tried to implement this logic in the provider to return a hardcoded object {sorcode:''} in case of null, it still returns null.

Code snippet on the page:

  ngOnInit() {         
    this.dbcon.getUser().then(dbvalue=>{
      console.log(dbvalue.val());
    });       
  }

Provider code (note that .once is a promise):

   getUser()
  {
    return firebase.database().ref(`/users/`).once('value', dataSnapshot => {
           if (dataSnapshot.val()==null)
           {
              {sorcode:''};
           }
           else
           {
              dataSnapshot.val();
           }
    });
  }

By placing the 'return' keyword within the IF loop and not before calling the promise as shown below, it throws an error on the page: "Cannot read property 'then' of undefined"

Provider code example:

   getUser()
  {
    firebase.database().ref(`/users/`).once('value', dataSnapshot => {
           if (dataSnapshot.val()==null)
           {
              return {sorcode:''};
           }
           else
           {
              return dataSnapshot.val();
           }
    });
  }

Even by adding the 'return' keyword within the IF loop and also before calling the promise, as shown below, the original issue persists - it returns null when the object does not exist.

Provider code excerpt:

       getUser()
      {
               return firebase.database().ref(`/users/`).once('value', dataSnapshot => {
var x=dataSnapshot.val();
               if (x==null)
               {
                  return {sorcode:''};
               }
               else
               {
                  return dataSnapshot.val();
               }
        });
      }

Answer №1

There is a crucial element missing in the code - the return statements are not included.

You can choose between two options:

return firebase.database().ref(`/users/`).once('value', dataSnapshot => {
       if (dataSnapshot.val() == null)
       {
          return {sorcode:''};
       }
       else
       {
          return dataSnapshot.val();
       }
});

or

firebase.database().ref(`/users/`).once('value', dataSnapshot =>
   dataSnapshot.val() == null ? 
     {sorcode:''} :
     dataSnapshot.val()
 );

UPDATE

According to the information provided here, it states that »returns firebase.Promise[…]«. It might be more appropriate to use:

firebase.database().ref(`/users/`).once('value').then(dataSnapshot => <return stuff here>);

It appears that the second argument serves as a "success callback".

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

Dynamic Variable Translation in Angular 8 using i18n

Within my app.component.html, there is a recurring element on every page: <h1 i18n="@@titleH1">{{title}}</h1> I created a shared service with setters and getters: ... title = new BehaviorSubject('Initial Title'); setTitle(title: s ...

Is there a way to conceal the progress output of an Angular build during test execution using Karma?

Currently, I am setting up a build process for an Angular 4 application and aiming to prevent progress output in order to keep the runner's logs clean. The project configurations were automatically created using angular cli (v1.0.1) By utilizing ng ...

the category is unspecified

As I try to deploy my code and run the build, TypeScript is throwing an error stating that 'object' is of type unknown. I am currently working on resolving this issue in my specific scenario. export default function Home() { async function send ...

Displaying images dynamically in React from a source that is not public

There are 3 image options being imported, determined by the value in the state which dictates which of the 3 to display. import csv from '../../images/csv.svg'; import jpg from '../../images/jpg.svg'; import png from '../../images/ ...

"Unlocking the Power of Monaco Editor: A Guide to Fetching CompletionItems from Your

Currently, I have integrated the fantastic monaco editor into my Angular 8 app for editing formulas. Everything is working fine, but now I need the list of suggestions (CompletionItems) to update dynamically. I have utilized the ngx-monaco-editor module a ...

What are the disadvantages of nesting CSS Grids within each other?

I have been exploring component-driven front-end frameworks like Angular and honing my skills in CSS Grid. My query is: Is it considered a bad practice to nest CSS Grids? In my main/root component, I have utilized CSS grid to create two elements: the nav ...

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

bidirectional data binding with programmatically generated input boxes

Is it possible to achieve two-way binding with dynamically created checkboxes? quali=[{class:"10",checked:false},{class:"12",checked:true},{class:"others",checked:true}]; <span *ngFor="let q_list of quali; let i=index" class="lists">  <in ...

Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected: Check out the TypeScript playground for reference. type ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Implement a universal JavaScript UI library into an Angular application

For my Angular application (Angular4.x), I am using the mapwize sdk which is a pure javascript library. I have successfully displayed a MapWize map by including the necessary scripts and styles in the index.html file, as shown below: <head> ...

Tips for effectively utilizing a Query or QueryTask with local graphics (GraphicsLayer)

Working on developing an ESRI map prototype using Angular4, I have successfully utilized the Draw tool to initiate a Query on a FeatureLayer to draw various graphics such as ConvexHull and Buffer. The primary goal was to create a clear Buffer graphic over ...

How to build a personalized dialog box with CdkDialogContainer

Currently, I am in the process of developing an Angular service (version 14.2.0) to implement a Tailwind/Flowbite dialog (which is known as a modal in Flowbite terminology). It appears that in order to ensure the proper DOM structure and class application ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields? interface Test{ name:string }; const temp :Test = JSON.parse('{ ...

How to Reload the Active Tab in Angular 5?

In my project, I have noticed that a listener in one of the tabs causes the entire tab to refresh, resulting in it displaying information from the first tab until I switch to another tab and then go back. 1) Is there a way to refresh only the current tab? ...

Implementing a video pause event trigger from a function in Angular2

Here is the content of my player.component.html: <video width="320" height="240" autoplay autobuffer [src]="videoSrc" (ended)="videoEnd()"> Your browser does not support the video tag. </video> <button (click)="pauseOrPlay()">pause/play ...

Utilizing React-Input-Mask (written in TypeScript) to conceal Material UI input within Formik forms

Issue with Formik Input and TextField Type Error <InputMask mask="99/99/9999" value={formik.values.phone} onChange={formik.handleChange} onBlur={formik.handleBlur} > {(inputProps: Pro ...

Ways to verify a formarray in Angular?

Using editable with formarray and my model: class Book { id: number; name: string; active: boolean; } List of all books: [ {id: 1, name: 'book1', active: true}, {id: 2, name: 'book2', active: true}, {id: 3, name: 'book3 ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...