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

Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure: { "user": [ { "id": 0, "data": [ { "userName": "iheb", "useremail": "", "userPassword": "kkk" } ], "questionnaireListe": [ { ...

Nested validation schema featuring conditional validation - yes, we've got it covered!

In my Formik object, I have set initial values as follows: {customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}} How can I create a conditional Yup validati ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

What is the best way to manage data types using express middleware?

In my Node.js project, I am utilizing Typescript. When working with Express middleware, there is often a need to transform the Request object. Unfortunately, with Typescript, it can be challenging to track how exactly the Request object was transformed. If ...

How to disable CSS transition on Angular 4 component initialization

I am facing a major issue with css transitions and Angular 4. The problem arises when using an external library that includes an input counter feature. Despite knowing that no additional styling is being applied to the wrapped input, the application has a ...

Angular allows you to pass an array of objects as FormData items

Is there a way to send FormData with an array of objects to an API? I have attempted the following: https://i.stack.imgur.com/BlYby.png This is the request payload. How can I retrieve all items with other data from my .NET Core C# API? public class Back ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

Require a property to be mandatory depending on the value of another property within a generic interface

Looking for a way to have one property affect the others in a react component interface? Here's an example of what I'm trying to achieve: export interface IMyAwesomeComponentProps<T = {}> { className: string defaultPath?: ISomeOthe ...

Utilizing TypeScript interfaces with additional parameter object members does not result in the anticipated compilation error

Consider the different types listed below: type Person = { id: string; name: string; }; interface PeopleRepository { getPerson(query: { id: string }): Person; } class Repository implements PeopleRepository { getPerson({ id, age }: { id: string; ...

Firebase: No user record exists for this identifier. It is possible that the user has been removed from the system

Utilizing Ionic2/Angular2 along with AngularFire2 and Firebase for user authentication during login. Upon successful registration of a user using email & password, I am able to log in with that same email & password without any issues. public fireAuth: ...

Tips for saving multiple pieces of data in a single field with Laravel

Is it possible to save multiple data at once using a simple form? controller $status= new PostTable(); $status->language = $request->language; blade <input type="checkbox" value="hindi" name="language[]" id="language"> Hindi model pro ...

How does TypeScript provide me with insights even before compiling with tsc?

As I follow the instructions for incorporating TypeScript into my existing React Native project here, the final step instructs me to: Run yarn tsc to type-check your new TypeScript files. However, when I check VSCode, I am already receiving feedback from ...

Generate detailed documentation for the functional tests conducted by Intern 4 with automated tools

I need to automatically generate documentation for my Intern 4 functional tests. I attempted using typedoc, which worked well when parsing my object page functions. However, it failed when working with functional test suites like the one below: /** * Thi ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

What is causing unexpected behavior when one service calls another service?

Let's say I make a call to a service that returns an observable, and if it doesn't encounter any errors, then another service should be called which also returns an observable. What I tried doing is calling both services separately, one after th ...

Tips for ensuring radiobuttons are defaulted to unchecked within a shared form group in Angular 2 and beyond

The radio buttons are linked to data from the database (Web-API). Below are my complete code snippets: component.html <!-- list of Questions --> <div formArrayName="questions"> <!-- <div *ngFor="let que of Questions; let ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Issue with running "ng generate" or "ng add" commands

While using angular version 8 in Termux Android ARM, I encountered an issue when trying to add the PWA and service worker to my website project. Here is the information about the angular version obtained from Angular CLI: $ ng version _ ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...