Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same.

getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any> {
    return combineLatest([obs1, obs2])
    .pipe(
      map(([prod1, prod2]) => {
          return prod1.find((prod: any) => prod.NombreProducto === prod2)
      }),
      toArray(),
      tap( a => console.log(a.length))
    )
}

The goal is to retrieve objects from obs1 whose NombreProducto matches the strings provided by obs2.

In response to Liam's request, I have added more code for better clarity:

// additional code snippets here...

Answer №1

To improve the functionality of your component, consider refactoring the code as shown below. By storing observables in private variables and passing them to the combine latest method within the service, you may see better results.

export class UpdatedComponent {
    ...
    municipalityId = "";
    private products$ = this.productService.getProducts();
    private municipalProducts$ = this.productService.getMunicipalProducts(this.municipalityId);
    
    ...
    
    // Utilize observable variables in getProduct() method
    getProducts() {
        this._gasStationService.getUniqueProducts(this.products$, this.municipalProducts$)
            .subscribe((data: any) => {
                this.products = data;
                if(!this.default) {
                    if (this.productId == '') {
                        this.productId = data[0].productId;
                        this.productName = data[0].productName;
                    }
                }
          this.getGasStations();
        });
    }
}

Answer №2

After much trial and error, I was able to find a solution. It turns out that concatMap(from) emits all at once, causing some issues with combineLatest. I managed to fix this by using

concatMap(a => from(a).pipe(delay(1))
. Thanks to everyone for their assistance.

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

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

The image located in the wwwroot directory is not displaying when the <img> tag is used. What could be causing this issue in ASP.NET and Angular?

My current project is housed in a folder named 'UsedCarsShop', which contains two subfolders: Frontend Within this folder is the 'UsedCarsShopFrontend' folder, where the Angular project is located. Backend The 'CarWebShop&apos ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...

How to retrieve the parameter value in Next.js version 13

I need assistance with extracting the parameter value from a GET endpoint: /api/image/id The directory structure is as follows: src/app/api/image/[id]/route.ts However, when attempting to access the id parameter, I am receiving a result of null. import { ...

One issue with Angular's mat-select is that it fails to close when the user clicks outside of

I have encountered an issue with angular material's select component that I am using to display options for selection. The problem arises when I click on the field and the list of options appears, but it does not close when I click outside the options ...

Exploring Angular 4: Performing tests on a component containing another component

I am currently conducting testing on my Angular application: ng test Below is the content of my html file (page-not-found.component.html): <menu></menu> <div> <h4> ERROR 404 - PAGE NOT FOUND </h4> </div> Afte ...

The Selenium tests are running smoothly, however, despite their successful execution, I am not receiving any pass results as the assertions seem

Currently, I am in the process of incorporating Selenium (v4.18.1) tests into an Angular web application specifically for the Microsoft Edge browser (v122.0.2365.59). The necessary Microsoft Edge WebDriver (v122.0.2365.59) has been successfully installed. ...

Changing the default component prefix in Angular to prevent TSLint warnings

When I create a new Angular 2 app with Angular CLI, the default component prefix is set to app-root for the AppComponent. However, if I decide to change the selector to something different like "abc-root", @Component({ selector: 'abc-root', ...

Is it possible to display the combined string when concatenating two strings?

Consider the following code snippet: const a = "url"; const b = "/route"; const c = a + b; Even though TypeScript knows the exact values of a and b, resulting in immutable constants, when concatenating both strings, the type of c is di ...

Model Mongoose TypeScript Interface Type

I am working with 2 models in my project import {model, Schema, Types} from 'mongoose' interface IResource { user : Types.ObjectId | IUsers, type : Types.ObjectId | IResourceData, value : number, lastUpdate : number | Date, ...

Encountering an issue while attempting to load in Angular2 RC4: Error: XHR error (404 Not Found) during loading

I encountered an exception while the application was loading on the browser. Here are the details of the error along with the configuration files: Error Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:5 ...

Refresh the main state by integrating the feature state using NGRX

A question arises regarding my app that utilizes ngrx to display blogs. Here is an overview of the main root state: import { Blog } from '../models/blog'; export interface AppState { readonly loaded: boolean; readonly blogs: {[key:number]: ...

npm-install fails to automatically install sub-dependencies

I'm currently working on an Angular 4 project that has specific dependencies. The project is functioning properly as it is. Now, my goal is to utilize this project in another project. I've added the original project to the package.json file (und ...

Experiencing a snag with Angular2 and angular2-jwt: encountering an issue with AuthHttp where the JWT must consist

Encountering an issue with AuthHttp despite receiving a valid token from the authentication. The token has been confirmed as valid on . Currently working with Angular 4. Here is my code: Sign-In Code signIn(login: string, password: string) { this.U ...

Controller in Angular checks for element overflow

In a grid, there are fields that may contain an Ellipsis when the content is too large. In such cases, a tooltip should display the full content. I have written a method in the component code to determine if an element has an ellipsis or not. However, whe ...

Encountering issues with utilizing global variables in Ionic 3

Using Ionic 3, I created a class for global variables but encountered an error Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError (http://localhost:8100/build/vendor.js:1590:86) at noProviderError Th ...

I am currently working on establishing a connection between Angular and MongoDB

I built a basic Angular application currently running on Local Host 4200. What is the process for saving form values and storing them in a MongoDB database? ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

Angular eliminates the use of directories in the URL during the routing process

I recently configured a local IIS and set up an application within a directory named test: When I accessed the URL in my browser: "http://localhost/test" The route for this scenario is defined as follows: const routes: Routes = [ { path: '&apos ...