Is there a way to ensure that the observer.next(something) received the value before executing observer.complete()?

I have been working on an Angular app where I am using a resolver to preload data in the component. Below is the code for the resolver:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {
return Observable.create(observer => {
  const searchProductsRequest = this.journeyDataService.searchProductsRequest;
    this.basketService.reset();
    this.progressService.subscribe(
    this.productsPublicApiService.getRecommendedProductCategoriesUsingGET(searchProductsRequest.vrn,
        searchProductsRequest.postcode),
      (response) => {
        // saving work type list
        observer.next(response.categories);
      },
      // handling server errors
      (err) => console.error(err)
    );
    observer.complete();
  });
}

In the component, I have the following code:

ngOnInit() {
   this.productCategoryList = this.route.snapshot.data.productCategoryList;
   console.log('resolve', this.productCategoryList);
 }

However, when checking the value of 'this.productCategoryList', it is null. This is because the response from the server arrives after the complete function is called, resulting in the data not being available for display.

Answer №1

If you want to ensure the "next" handler is fully executed, include the complete call within your code snippet:

(response) => {
        // Save work type list
        observer.next(response.categories);
        observer.complete();
      },

There may be a more standard approach to solving your issue, but a clear understanding of functions like

getRecommendedProductCategoriesUsingGET
and progressService.subscribe is necessary for proper implementation.

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

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

Using ngFor in Angular 6 to create a table with rowspan functionality

Check out this functional code snippet Desire for the table layout: <table class="table table-bordered "> <thead> <tr id="first"> <th id="table-header"> <font color="white">No.</font> </th> <th id="table-hea ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Error in TypeScript: The property "component" is not found on the React MUI MenuItem

I am currently working with the react mui MenuItem component and I am trying to turn a menu item into a link. Here is how I have attempted to achieve this: <MenuItem component={<Link href={`/backend/api/exam/${row.id}/result`} />} className={c ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

Encountering a CORS error while utilizing a Node.js Express API with an Angular frontend

While developing an API using Node.js, Express, and MongoDB, I encountered a CORS error when trying to call the API from an Angular application. Strangely enough, the API works fine when deployed on Render, but throws an error locally. Error: Access to XM ...

Exploring TypeScript reflections within a specific namespace

(Building upon previous discussions about dynamically loading a TypeScript class) If I am currently within a namespace, is there a method to reference classes within the namespace in order to utilize 'reflection' to invoke their constructors? n ...

What is the correct way to utilize window.scrollY effectively in my code?

Is it possible to have a fixed header that only appears when the user scrolls up, instead of being fixed at the top by default? I've tried using the "fixed" property but it ends up blocking the white stick at the top. Adjusting the z-index doesn&apos ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

Angular application featuring scrolling buttons

[Apologies for any language errors] I need to create a scrollable view with scroll buttons, similar to the image below: Specifications: If the list overflows, display right/left buttons. Hide the scroll buttons if there is no overflow. Disable the le ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

`Angular 10 project fails to include JWT refresh token in cross-origin requests`

Our development setup includes an Angular front end and a web service running on a different port on the same machine. The web service is configured to allow access from localhost and the port hosting the Angular application. We are utilizing JWT authenti ...

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

The unexpected behavior of rxjs withLatestFrom

import { of, Subject, interval } from 'rxjs'; import { tap, startWith, map, delay, publishReplay, publish, refCount, withLatestFrom, switchMap, take } from 'rxjs/operators'; const source$ = new Subject(); const res ...

tips for incorporating datatable into ng bootstrap modal within an angular application

I am trying to create a data table within an ng-bootstrap modal in Angular using Bootstrap and the angular-data tables module. My goal is to display the data table specifically within a bootstrap modal. ...

Could you please clarify the type of event on the onInputChange props?

I am encountering an issue with using React.ChangeEvent on the mui v4 autocomplete component as I prefer not to use any other method. However, I keep getting an error indicating that the current event is incompatible. const handle = (e: React.ChangeEv ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...