Ionic 4 - Best practices for handling asynchronous data with multiple observables

I successfully accessed this route:

http://localhost:8100/questions/question?id=3

However, I am facing a challenge in handling two subscribers simultaneously.

The first subscriber is responsible for loading the questions array from an external service.

The second subscriber is tasked with retrieving the desired Question object based on the route parameter.

app_data:AppData;
question:Question;

ngOnInit() {
  this.appService.app_data.subscribe((v) => { this.app_data = v; });

  this.route.queryParams.subscribe(p => {
    this.question = this.appService.app_data.questions.find(i => i.id === params.id);
  });
}

The issue arises when I navigate to this route as it attempts to filter the array before it is fully loaded by the service.

ERROR TypeError: Cannot read properties of undefined (reading 'find')

Is there a mistake in my approach?

Answer №1

Suggested approach is to utilize the combineLatest rxjs operator in order to merge multiple observables and extract the most recently emitted value.

Upon emission of a value by any observable, extract the most recent value emitted by each observable.

import { combineLatest } from 'rxjs';

combineLatest([this.appService.app_data, this.route.queryParams]).subscribe(
  ([appData, param]) => {
    this.app_data = appData;
    this.question = appData.questions.find((i) => i.id === param.id);
  }
);

See Demo on StackBlitz


Additional Tip:

forkJoin is designed to defer emission until all Observables have completed and then emit their final values. However, in cases like route.params, route.queryParams observables that will never complete, the use of forkJoin is ineffective.

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

Prevent Angular Router from Initiating NavigationStart

Can the NavigationStart event be prevented in Angular? I am attempting to display a customized confirmation modal when the user attempts to switch routes. constructor(private router: Router) { if(val instanceof NavigationStart){ //Display th ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Can you identify the syntax of this LESS variable called @grid-breakpoints with breakpoints for xs at 0, sm at 576px, md at 768px, lg at 992px, and xl at

While exploring the bootstrap less port, I came across this interesting syntax: @grid-breakpoints: xs 0, sm 576px, md 768px, lg 992px, xl 1200px; What exactly is this? It doesn't seem to be a map or an array... How can I retriev ...

Using Angular 2 with the @ngtools/webpack for Ahead of Time (AOT)

I'm attempting to implement AOT in Angular 2 using webpack and @ngtools/webpack. During compilation, I encounter no errors. However, upon opening the site in the browser, a console error occurs: No NgModule metadata found for 'AppModule' ...

Is it necessary to install ng-bootstrap if my project was built using the Bootstrap 4 alpha theme in Angular 4?

I am currently utilizing the SB-Admin-BS4-Angular-4-master theme in Angular 4. The theme includes a link to . My goal is to implement Bootstrap modals in my code. Following the documentation provided in the theme, I integrated the modals as per instruction ...

Learn how to dynamically add and remove a CSS class from an element using a scroll event in Angular 7

My goal is to create a navbar that gains a "fixed-top" class during scrolling and removes it when it reaches the top of the page. I've written the following script, but unfortunately, it's not working as expected. import { Component, OnInit, Af ...

Can you explain the distinction between using get() and valueChanges() in an Angular Firestore query?

Can someone help clarify the distinction between get() and valueChanges() when executing a query in Angular Firestore? Are there specific advantages or disadvantages to consider, such as differences in reads or costs? ...

The Typescript decorator is unable to access the property type within its own scope

I am currently in the process of developing a dependency injector for use in my VUE js project. Recently, I created an Inject decorator with the intention of accessing a property type. It was functioning perfectly fine yesterday, but now it seems that som ...

Having issues with unexpected token in Typescript while using "as HTMLElement" type?

I recently started learning Typescript and I encountered an error while using the HTMLElement type in a forEach loop: ERROR in ./app/javascript/mount.jsx Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: /Users/me/projects/m ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Random select triggering when modifying a different section of state

In my application powered by NxRx (v7), I have a specific "feature" state that is structured as shown below: State export interface DataPageState { dataReceivedTimestamp: number; formData: PageSaveDataState; // <--- setting ...

How does the call method on array.prototype.includes work with arguments x and y?

Curious about the functionality of array.prototype.includes.call(x, y);. Discovered that includes() confirms if an array has the specified value and provides a true or false result. Learned that call() invokes this alongside any optional arguments. The ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Tips for minimizing disagreements while implementing optional generic kind in TypeScript?

An issue arises in StateFunction due to its optional second generic type that defaults to a value. Even when omitting this second generic, undefined still needs to be passed as an argument, which contradicts the idea of it being optional. While making arg ...

Is it beneficial to utilize an interface for constructing a class model?

The Interface: export interface IAddEditGeneralDictionary { Code: string; StartDate?: Date | string; FinishDate?: Date | string; Name: string; } The Realization: export class AddEditGeneralDictionary implements IAddEditGe ...

Utilizing Angular 2 to Implement Remote Validation Error Handling in Forms

Whenever I submit a form to my backend, there is a chance that I will receive a response with HTTP code 400, which means that the validation has failed. An example of the response from my backend could be: { "status":"fail", "data":{ "email": ...

Troubleshooting Problem with Angular Material 2's Mat-Paginator [Length] Bug

Utilizing the mat-paginator component for a table, I am facing an issue where I am unable to dynamically set the length of the paginator based on the total number of results retrieved from an API call. Despite trying various methods like setting it in the ...

Is it possible to create two subclasses where the methods return the types of each other?

I am faced with a situation where I have two classes that rely on each other's methods: class City { (...) mayor(): Person { return this.people[0]; } } class Person { (...) birthCity(): City { return this.cities.birth; } } ...

Managing arrays in local storage with Angular 2+

I seem to be missing a crucial element in my endeavor to save and retrieve an array in local storage within my Angular 4 application. The array is fetched from the server and stored in a variable named 'aToDo' with type 'any', like so: ...