"Upon subscribing, the array within the object is found to be

I am encountering a synchronization issue while trying to retrieve an element after making multiple HTTP requests. Below is the code I have posted:

Get function in my service:

get() {
return new Observable(project => {
  this.channelsService.get().subscribe(
    stations => {
      this._stations = stations;
      this._stations.forEach((station) => {
        station.cssClass = this.channelsService.getCss(station.id.split('/').pop());
        station.plstation$thumbnails = this.channelsService.getThumbnails(station.id.split('/').pop());
        if (station.plstation$callSign !== '') {
          const watchliveUrl = this.watchLiveApi + station.plstation$callSign + '/?schema=1.0.0';
          this.http.get(watchliveUrl).subscribe(data => {
            const body = data.json();
            station.currentListing = body.currentListing;
            station.nextListing = body.nextListing;
            project.next(stations);
            project.complete()
          });
        }
      });

    }, (error) => {
      this.mapErrorService.mapError(error, 'Listing service (1)');
    });
});

}

get() used and subscribe:

 constructor(private listingService: ListingService) {
this.listingService.get().subscribe((stations) => {
  this.stripDetails.channelList = stations;
  // stations[6].currentListing Not undefined
  console.log(stations);
  // Now is undefined
  console.log(stations[6].currentListing);

});  }

How can I set define stations[6].currentListing?

Answer №1

Converting the Observable from http.get() into a Promise is done in this code snippet, but unfortunately, the Promise is not utilized. As a result, even though the stations variable is defined at one point, the currentListing attribute will remain undefined due to the incomplete status of the Promise.

When dealing with Observables or Promises, it's crucial to ensure that you wait for the results before proceeding. In the context of using promises in this scenario, it's important to gather all the promises together and postpone outputting the project until all promises have been fulfilled.

An example approach could be:

get() {
return new Observable(project => {
  this.channelsService.get().subscribe(
    stations => {
      this._stations = stations;
      let responses = this._stations.map((station) => {
        station.cssClass = this.channelsService.getCss(station.id.split('/').pop());
        station.plstation$thumbnails = this.channelsService.getThumbnails(station.id.split('/').pop());
        if (station.plstation$callSign !== '') {
          const watchliveUrl = this.watchLiveApi + station.plstation$callSign + '/?schema=1.0.0';
          return this.http.get(watchliveUrl).map(data => {
            const body = data.json();
            station.currentListing = body.currentListing;
            station.nextListing = body.nextListing;
          });
        }
      });
      // Ensuring all requests are completed before proceeding.
      Rx.Observable.forkJoin(...responses).subscribe(() => {
            project.next(stations);
            project.complete()
      });

    }, (error) => {
      this.mapErrorService.mapError(error, 'Listing service (1)');
    });
});

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

Parsing a Json object that contains a field with two distinct types, one of which is recursive

In my project, I have a TypeScript component that retrieves JSON data, and I need to parse this JSON in C# to work with the objects. However, due to the presence of: multiple type fields recursion it's becoming challenging to understand how the dese ...

Changing the name of a tab within a p-tabview

Setting up a p-tabview with tabs containing specific content involves the following code: <p-tabView class="tabmain" > <ng-container *ngFor="let tab of tabs"> <p-tabPanel [header]="tab.header" > ...

What is the best way to handle both local and global ajax events in jQuery?

After recently transitioning from Prototype to jQuery, I am encountering some challenges. My application involves multiple AJAX requests, where I want certain global events to take place in 95% of cases, such as displaying or hiding a loading indicator. A ...

Cross-Origin Resource Sharing problem: "Preflight request response does not meet access control criteria"

I'm currently tackling a Vue.js/Nuxt.js project that involves sending API requests to 'https://app.arianlist.com'. However, I've encountered some CORS challenges and came across this error message: "Access to XMLHttpRequest at &ap ...

Despite my attempts to assign null as a value to the key named null, the result continues to be undefined

I created a custom parseJSON function that is intended to produce the same result as JSON.parse when given the same input. There's also a helper function named getParsed() that correctly parses strings into their respective data types. However, I&apos ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

Do I have to specify the protocol when loading jQuery?

Underneath is the code snippet: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script> <script type="text/javascript"> console.log(jQuery); </script> This code works perfectl ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

Resolving Jest error in React JS unit tests

While working on a unit test for React code, I encountered an issue with a particular action. For example, suppose I have the following line in testing.js: const images = require.context('../../../media/promotions', true); Here is the unit tes ...

Adding external JavaScript and jQuery files in Nuxt 3: A step-by-step guide

After successfully adding the CSS files in Nuxt 3 and nuxt.config.ts, everything is working as intended. The next step involves determining the ideal folder to add these script files. Any suggestions on the best approach to solve this issue? ...

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Guide to manually creating and accessing an array of objects in Firebase using Angular

I have successfully generated a dynamic list of cards from an array of objects stored in the user.component.ts file. user.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from '../service/auth.service& ...

What is the best way to link a URL ID to a specific piece of content stored on

Is it possible to display a product without creating separate html pages for each one using unique IDs? I prefer the layout style of Pinterest. For example, with a URL like /product/12345 When a user clicks on /product/12345, the content should be rende ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here My code successfully shows and hides the navigation items, but it's not updating the burger icon No console errors or warnings are present This is my HTML: <nav> ...

npm run serve does not utilize vue.config.js configurations for devServer

I encountered a CORS issue when trying to use my flask HTTP APIs with my VUE js webapp on the development server. To resolve this, I decided to set up a reverse proxy by creating a vue.config.js file in the project directory: module.exports = { devServer ...

Navbar currently active does not switch when moving to a different page

I'm experiencing some issues with the Navbar on my website. I want the active tab to change as users navigate through the different pages. Since I'm using a base template, I don't want to duplicate the navbar HTML/CSS for each page, so I th ...

Exploring the magic of the (!!!) operator in JavaScript!

The !! operator proves to be quite helpful when converting non-boolean data types into Boolean values, mainly for "True" conditions. However, when it comes to false conditions, is using !!! necessary? ...

An Iframe lacks the ability to showcase HTML content, unlike a browser which is capable of doing

I'm struggling to get my Iframe to show the html string properly. Here's the content of the string: var='<BODY style="MARGIN: 0px" bgColor=#ffffff marginwidth="0" marginheight="0"> <SCRIPT language=JavaScript> var Caller_User_Ty ...