Angular function implementing a promise with a return statement and using the then method

I have a function in which I need to return an empty string twice (see return ''. When I use catch error, it is functioning properly. However, I am struggling to modify the function so that the catch error is no longer needed. This is my current function:

agencies$: Observable<Agency[]> = this.afs.collection<Agency[]>('agencies')
    .valueChanges()
    .pipe(tap(console.log),
      mergeMap((agencies: Agency[]) => from(agencies)),
      mergeMap((agency: Agency) => {
        return forkJoin([
          this.afStorage.storage
            .refFromURL('gs://agency-logos-paid-keeper')
            .child(`/thumbnails/${agency.agencyId}_700x100.png`)
            .getDownloadURL().then(url => url).catch(error => {
            return '';
          }),
          this.afStorage.storage
            .refFromURL('gs://benefit-cards-paid-keeper').child(`/${agency.agencyId}_200x200.png`)
            .getDownloadURL().then(url => url).catch(error => {
            return '';
          })])
          .pipe(
            tap(([logoUrl, benefitCardPhotoUrl]) => console.log('a', logoUrl, benefitCardPhotoUrl)),
            map(([logoUrl, benefitCardPhotoUrl]) => ({
                ...agency, logoUrl, benefitCardPhotoUrl
              })
            ), catchError((error) => {
              return of({...agency});
            }));
      }),
      map((agency: Agency) => [agency]),
      scan((agencies: Agency[], agency: Agency[]) => {

        const agencyExists = agencies.find(a => a.agencyId === agency[0].agencyId);
        if (!agencyExists) {
          return [...agencies, ...agency];
        }
        return agencies;
      }));

I am looking to eliminate the .catch(error) after then (both occurrences), but every attempt results in an error. How can I remove the catch error while still ensuring there is a return statement? It might seem like a basic question, but I'm stuck and unable to solve it.

Answer №1

Over time, I've learned that mixing promises and Observables can lead to complications. By transitioning the promises to Observables in your code, everything appears to be functioning smoothly

 agencies$: Observable<any> = this.afs
    .collection<Agency[]>("agencies")
    .valueChanges()
    .pipe(
      tap(console.log),
      mergeMap((agencies: Agency[]) => from(agencies)),
      mergeMap((agency: Agency) => {
        return forkJoin([
          from(
            this.afStorage.storage
              .refFromURL("gs://agency-logos-paid-keeper")
              .child(`/thumbnails/${agency.agencyId}_700x100.png`)
              .getDownloadURL()
          ),
          from(
            this.afStorage.storage
              .refFromURL("gs://benefit-cards-paid-keeper")
              .child(`/${agency.agencyId}_200x200.png`)
              .getDownloadURL()
          )
        ]).pipe(
          tap(([logoUrl, benefitCardPhotoUrl]) =>
            console.log("a", logoUrl, benefitCardPhotoUrl)
          ),
          map(([logoUrl, benefitCardPhotoUrl]) => ({
            ...agency,
            logoUrl,
            benefitCardPhotoUrl
          }))
          // catchError(error => {
          //   return of({ ...agency });
          // })
        );
      }),
      map((agency: Agency) => [agency]),
      scan((agencies: Agency[], agency: Agency[]) => {
        const agencyExists = agencies.find(
          a => a.agencyId === agency[0].agencyId
        );
        if (!agencyExists) {
          return [...agencies, ...agency];
        }
        return agencies;
      })
    );

https://i.stack.imgur.com/CIVvM.png

Take a look at this demonstration visualization

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

Utilize the parameters from the config.json file within the application

We've integrated the Google Maps API into our project and have generated a key for it. Currently, this key is hardcoded in one of our module files. However, we want to enhance security by moving this key into the config.json file. This way, when we pu ...

Error: 'ngForOf' is not recognized as a valid property of the 'tr' element

Since this afternoon, I've been facing a challenge that I can't seem to grasp. The issue lies within a service I created; in this file, there is an object from which I aim to showcase the data in a loop. An error message is displayed: NG0303: C ...

Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved. For unit testing purposes, I am creating mock versi ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

What is the best way to organize the data retrieved from the api into a map?

In my search page component, I display the search results based on the user's query input. Here is the code snippet: "use client"; import { useSearchParams } from "next/navigation"; import useFetch from "../hooks/useFetch&qu ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Having trouble launching the application in NX monorepo due to a reading error of undefined value (specifically trying to read 'projects')

In my NX monorepo, I had a project called grocery-shop that used nestjs as the backend API. Wanting to add a frontend, I introduced React to the project. However, after creating a new project within the monorepo using nx g @nrwl/react:app grocery-shop-weba ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Verify an entry with exactly 7 numerical digits

When inputting data, the user is limited to entering only 7 figures. If more than 7 figures are entered, an error message will display: "You need 7 digits". For instance, if the user enters something like this: 12345678910 The error message is correctly ...

What about a toggle for read-only TypeScript everywhere? (parameters in functions)

Is there a method, whether through a macro library, an eslint rule, a tsconfig setting, a special global.d.ts file, or some other means, to automatically set function arguments as readonly by default? // I wish for the compiler to transform this: functio ...

Undefined error when refreshing Angular page

One particular page on my forum-like website is causing issues with refreshing. In my project, users can log in, view their profiles as well as others'. However, when I refresh a profile page, no data loads from the server and an error appears in the ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Using Angular 2 to implement a custom dropdown feature with the ngModel directive

I've created a unique custom component that displays employment types in a dropdown menu and allows the user to select one. Here is the code for the component: import { Component, OnInit } from "@angular/core"; import { EmploymentType } from '. ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

What is the best way to refresh or reload a child component in Angular?

I have a transaction.component.html file that displays the app-deal-partners component. Every time the delete function is triggered, I want to refresh and reload the child component, which is the app-deal-partners component. I need to reload <app-deal- ...

Employing ngModel in an option dropdown

I am having trouble passing an attribute from an API call to a submit function. I suspect it might have something to do with either the option select or how the input is being formatted. Encountering the error Error: No value accessor for form control wit ...

Changing the size of a div component using Angular 6

Currently, I am working on implementing Angular's element resize feature. I am utilizing this library: https://github.com/mattlewis92/angular-resizable-element Here is my custom module: import { ResizableModule } from 'angular-resizable-elemen ...