Responding with a signal in Angular Firebase Functions

I'm currently working on integrating Angular 18 with Firebase Cloud Functions to interact with a MongoDB database. I have opted to use signals for this purpose, but I keep encountering a type error.

Below is the content of my index.js file:

exports.atlasWordObservable = functions.https.onCall((lemma) => {
  const query = { l: lemma };
  return mongodb.connect().then(() => {
    return collection.find(query).toArray();
  });
});

After defining the function in the file above, I attempt to call it as shown below:

import { getFunctions, httpsCallable } from '@angular/fire/functions';

...

entrySingleArray$ = signal<Entry[]>([]);
functions = getFunctions();
atlasLemma = httpsCallable(this.functions, 'atlasWordObservable');
emptyEntry: Entry[] = [{ id: 0, alpha: 0, l: ''}];

getFireLemma(lemma?: string): Observable<Entry[]> {
  return (
    lemma
      ? from(this.atlasLemma({name: lemma}))
      : of(this.emptyEntry)
  ).pipe(
    tap((response) => {
      this.entrySingleArray$.set(response);
      console.log(this.entrySingleArray$());
    }),
  );
}

However, while executing the code, the IDE highlights an error at the return line and displays the following message:

Type 'Observable<HttpsCallableResult> | Observable<Entry[]>' is not assignable to type 'Observable<Entry[]>'.

As per my understanding, I have two options available: either convert the returned value of the function from

HttpsCallableResult<unknown>
to Entry[] (I'm unsure how to do this), or modify the function in javascript to return the desired Entry[] type, which seems only possible if I switch to using TypeScript.

Your assistance in resolving this issue would be greatly appreciated.

Answer №1

To properly handle the data coming from the HttpsCallableResult, you need to cast it as an array of type Entry[] using the map operator provided by RxJS.

import { from, Observable, of, tap, map } from 'rxjs';

getFireLemma(lemma?: string): Observable<Entry[]> {
  return (
    lemma
      ? from(this.atlasLemma({ name: lemma })).pipe(
          map((x: HttpsCallableResult<unknown>) => x.data as Entry[])
        )
      : of(this.emptyEntry)
  ).pipe(
    tap((response) => {
      this.entrySingleArray$.set(response);
      console.log(this.entrySingleArray$());
    })
  );
}

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

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

The use of the cache-control request header field is prohibited when attempting to sign in with an Angular frontend during the

I recently developed an application using Angular with a Java backend in Spring. However, I'm facing an error when trying to log in and it's related to CORS policy. Whenever I try to login, I receive the following error message: Access to XMLH ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

What is the recommended data type for the component prop of a Vuelidate field?

I'm currently working on a view that requires validation for certain fields. My main challenge is figuring out how to pass a prop to an InputValidationWrapper Component using something like v$.[keyField], but I'm unsure about the type to set for ...

When working with Angular and evaluating code, I encounter an issue related to the environment that

Here is my code snippet: let var1="environment.test"; console.log(eval(var1)); But when I run it, an error occurs: ERROR ReferenceError: environment is not defined However, if I modify the code to be like this: console.log(environment.test); it works ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

Ways to control the variable `@input` based on certain conditions

I'm trying to access values using @Input() and need to manipulate them with an iterator. How can I accomplish this? Below is the code snippet: @Input() events: Observable<Array<CalendarEvent>>; //need manipulation @Input() currentEvent: ...

Error: When using the axios package in TypeScript code within a Firebase cloud function, there is an issue with reading the property 'post' which is undefined

I am attempting to implement the following logic in a Google Cloud Function. When I run this function using the emulator, I consistently encounter the error message ⚠ functions: TypeError: Cannot read property 'post' of undefined I have tried ...

Define the data type for the toObject function's return value

Is it possible to define the return type of the toObject method in Mongoose? When working with generics, you can set properties of a Document object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various v ...

Tips for efficiently reusing validation rules across multiple endpoints in Express Validator

In order to streamline my coding process, I am interested in finding a way to reuse Express Validator schemas across multiple endpoints. Rather than creating separate schemas for each endpoint (such as POST and PUT requests), I would like to have a singl ...

What is the correct syntax for using the apply method in combination with console.log()?

Below is the class I've created to capture the console.log function in my application. This allows me to review logs on devices where accessing the browser console isn't easy, and also helps in bundling captured logs for error reporting later on. ...

A guide to setting initial values in Angular 2 using TypeScript

My Rank class includes attributes for "loses" and "wins" obtained from a web service. I need to calculate the "points" attribute based on these values. For example: for(int i = 0; i<loses; i++{ points += 1; } for(int i = 0; i<wins; i++{ point ...

How do I loop through each object within an observable that contains an array of objects in Angular 2?

Hey everyone! I'm currently in the process of upgrading my skills to Angular 2 and I have a few questions. One of them being, how can I iterate through each object in an observable array object? I was able to successfully retrieve data from "api/v1/e ...

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

The file 'angular.json' needed for the workspace could not be located

Upon attempting to launch my Angular application using ng serve, I encountered the following error message: Local workspace file ('angular.json') could not be found. Error: Local workspace file ('angular.json') could not be found. ...

Manipulating variables across the entire app in Angular is made possible through the use of

Is there a way to access and modify global variables in Angular 8? I've tried creating a shared service like this: export class SharedService { globalLanguage:string; setGlobalVar(currentLanguage:string) { this.globalLanguage = current ...

Angular Error: Argument must be included in the dependency array

While making changes to a dialog form, I encountered an error. Instead of using a dialog form, I want to switch to a regular form. However, when I remove @Inject(MAT_DIALOG_DATA) from the constructor, I get an error. Any suggestions on how to resolve thi ...

Troubleshooting the Issue with Angular Material Dialog Imports

Hey there, I'm trying to utilize the Angular Material dialog, but I'm encountering issues with the imports and I can't seem to figure out what's wrong. I have an Angular Material module where I imported MatDialog, and I made sure to i ...

Typescript Class Getting Vacant

When working with a specific setup in TypeScript, I encountered a situation where at runtime in JavaScript, I ended up with empty class objects. This occurred when two classes referenced each other, leading to one of them being empty within the scope of th ...

Utilizing Angular 2 within JSP on the Spring MVC framework

My query is akin to this previously asked question. The scenario is as follows: An existing web project utilizes Spring MVC, Angular1.x, JSP, and JavaScript among others. The layout of the page has already been structured using tiles technology. I am task ...