Extract Subscription Information from the .subscribe function in Angular

After calling the subscriber, I aim to fetch the events. This code successfully achieves this:

 getCalendarData(){
      var body = JSON.stringify({"cid": "etNG3V61LWS6Pzkeb_omuZGMVAOLd1_70tRQblVizWQ~",
      "seldt":"2018-09-18"}); 
      var headers = new HttpHeaders();
      headers.append('Content-Type', 'application/json');

      return this.httpClient.post(this.apiUrl, body, { headers: headers })

    }

The above code runs perfectly and returns a JSON object.

However, when I try to call this method within getCalendarEvents(), I encounter a problem with returning the events due to the asynchronous nature of subscribe. How can I pass the events while requiring a return type?

 getCalendarEvents(): Array<CalendarEvent> {
         var listCal:any = []
         this.getCalendarData().subscribe((data: any) => {
          listCal = data;
              console.log('listCal data: ', listCal);  

             let startDate: Date,
             endDate: Date,
             event: CalendarEvent;
             let colors: Array<Color> = [new Color(200, 188, 26, 214), new Color(220, 255, 109, 130), new Color(255, 55, 45, 255), new Color(199, 17, 227, 10), new Color(255, 255, 54, 3)];
             let events: Array<CalendarEvent> = new Array<CalendarEvent>();
             for (let i = 1; i < listCal.length; i++) {
                  event = new CalendarEvent(listCal[i].title, new Date(listCal[i].date), new Date(listCal[i].date), false, colors[i * 10 % (listCal[i].colour.length - 1)]);    

                  events.push(event);     
              }
             //console.log(events);     
             return events;
           }
         );    

         //return events; HERE the events has no data because I am outside the .subscribe!
    }

Answer №1

To handle this situation properly, you must approach it as an `async` function. There are a couple of ways to do this:

import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

getCalendarEvents(): Observable<Array<CalendarEvent>> {
  return this.getCalendarData().pipe(map((data: any) => {
    // Your parsing logic...
    return events;
  }));
}

// or:

getCalendarEvents(): Observable<Array<CalendarEvent>> {
  const result: Subject<Array<CalendarEvent>> = new Subject<Array<CalendarEvent>>();
  this.getCalendarData().subscribe((data: any) => {
    // Your parsing logic...
    result.next(events);
    result.complete();
  });
  return result;
}

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

What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error: ./components/Hero.tsx:2:0 Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v' 1 | import React, { useState } from 'react'; > 2 | import Video from '../ ...

Consecutive requests to APIs using RxJs

Is it possible to efficiently make sequential API calls using RxJs? The challenge lies in the fact that the first Observable emits an array, and for each item in this array, a custom URL should be set for the next call. Additionally, certain conditions nee ...

Streamlining the deployment process of Angular applications on IIS through automation tools such as Docker and Jenkins

I am currently manually deploying my Angular application on an IIS server by copying the build from my system to a specific location on the server. The code for my application is stored in a TFS repository. My application's backend is powered by Mul ...

Removing duplicate elements from an array in TypeScript

In my TypeScript code, I am working with an array of objects and need to remove any duplicates. The code below accomplishes this task: const uniqueObjects = Array.from(new Set(nonUniqueObjects.map((x) => { return JSON.stringify(x); }))). ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

What is the process for changing a field in a document on firestore?

Is there a way to modify a specific field in a firestore document without retrieving the entire document beforehand? ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

When attempting to retrieve information from the API, an error occurred stating that property 'subscribe' is not found in type 'void'

I've attempted to use this code for fetching data from an API. Below is the content of my product.service.ts file: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, Observ ...

Exclusive gathering to discuss @Input attributes

Is there a way to determine if all of the input properties in my component have been initialized with data? Are there any specific events that can help indicate this? Thank you for your assistance! ...

What steps can I take to avoid encountering the `@typescript-eslint/unbound-method` error while utilizing the `useFormikContent()` function?

Recently, I updated some of the @typescript-eslint modules to their latest versions: "@typescript-eslint/eslint-plugin": "3.4.0", "@typescript-eslint/parser": "3.4.0", After the update, I started encountering the fo ...

The Angular application has been successfully deployed on a Tomcat server as a war

I am planning to deploy a single page application (SPA) developed in Angular, along with various static files like *.css, .js, /assets/, all packed inside a war file on Tomcat. The issue I am facing is that whenever a user enters a path that does not corr ...

What causes the package-lock.json to contain newer versions of packages compared to package.json following a new npm installation in Angular?

Back in the year 2017 or around that time, npm reportedly made a decision to automatically update packages in package-lock.json if the versions listed in package.json were higher. An interesting issue I've noticed is that my project seems to be upgra ...

Navigating the maze of Material UI in React with TypeScript

I have a functioning code, but I am trying to incorporate Material UI into it. However, when I replace 'input' with 'TextField', I encounter the following error: Uncaught (in promise) Error: Request failed with status code 422 at cr ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

Is there a way to convert a File into a byte array and then save it in a database using Angular and ASP.Net Core?

Hey everyone, I'm fairly new to working with Angular and I've hit a roadblock when trying to implement file-upload functionality in my Angular application. The technologies I am using include Angular, ASP.Net Core, and Sqlserver. I am tasked wi ...

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

I am having trouble using a form to filter by year in Angular

Here's an example link to view: https://stackblitz.com/edit/angular-ivy-byvfjy?file=src/app/ofertas/filtro-ofertas/filtro-ofertas.component.ts I have a requirement to filter the table by year. https://i.sstatic.net/Bfu7b.jpg However, I keep encount ...

Adding jQuery into an Angular HTTP request

I've been searching for a solution here, but I haven't been able to find one yet. It's possible that I'm just not looking in the right place! I'm attempting to execute some jquery code after loading json data using Angular's ...

You cannot assign an array of 'Contact' objects to a single 'Contact' parameter

During the development process, I encountered an error while trying to add a new contact. The error message states: Error: src/app/contacts/contacts.component.ts:32:28 - error TS2345: Argument of type 'Contact[]' is not assignable to parameter o ...