Creating an asynchronous request mimic similar to AJAX in Angular 7

Within my current project, I am utilizing a full calendar that loads events dynamically from a database. However, I encountered an issue when attempting to add events to the calendar. It seems like there might be a synchronization problem with the httpget method that prevented me from resolving the issue.


this.events = [];
this.holidayList = [];

this._holidayService.getHolidayArray().subscribe((result: any[]) => {
  for (let i = 0; i < result.length; i++) {
    this.events.push({ "title": result[i].title, "start": result[i].start });
  }
});

this.options = {
  plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
  selectable: true,
  selectMirror: true,
  select: function (arg) {
    var start = arg.start.toString();
    var date = start.slice(8, 10);
    var year = start.slice(11, 15);
    var month = start.slice(4, 7);

    // 
    if (month === "Jan") month = '01';

    ...
   
  },
  defaultDate: '2019-07-01',
  header: {
    left: 'prev,next',
    center: 'title',
    right: 'month,agendaWeek,agendaDay'
  },
  events: this.events

}
}

getHolidayArray() {
return this.ExecuteGet("api/HolidayCalendar/GetTitles");
}

If I try

this._holidayService.getHolidayArray().then(events => { this.events = events; });

an error "then doesn't exist on type observable"

Answer №1

Refer to the 'Change Detection' segment of the link provided in your post (https://www.primefaces.org/primeng/#/fullcalendar). It's important to note that simply pushing new data into the events array may not work as expected. Instead, consider creating a fresh this.events instance after going through your loop.

this._holidayService.getHolidayArray().subscribe((result: any[]) => {
  const events = [];
  for (let i = 0; i < result.length; i++) {
    events.push({ "title": result[i].title, "start": result[i].start });
  }
  this.events = [...this.events, ...events];
});

Answer №2

If you're working with RxJS 5.5 or newer, here's a solution to consider:

Try out the following code snippet:

retrieveHolidaysList() {
  return this.ExecuteGet("api/HolidayCalendar/GetTitles");
}

----

import { map } from 'rxjs/operators';

this.calendarEvents = [];
this.holidays = [];

this._holidayService.retrieveHolidaysList()
  .pipe(
    map((result: any[]) => result.map(item => ({
      title: item.title,
      start: item.start
    })))
  )
  .subscribe((result: any[]) => this.calendarEvents = 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

Utilize switchMap to sequence calls

My goal is to execute rest requests sequentially using switchMap(...) from RxJs. Here is the object: export class Transaction { constructor( public id: string, public unique_id: string, public name: string, public status: string, pu ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Connecting two divs with lines in Angular can be achieved by using SVG elements such as

* Tournament Brackets Tree Web Page In the process of developing a responsive tournament brackets tree web page. * Connection Challenge I am facing an issue where I need to connect each bracket, represented by individual divs, with decorative lines linki ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

What is the best way to categorize array items based on a specific TypeScript type?

Imagine having the following data array: const information = [ { group: 'z', name: 'hello' }, { group: 'z', name: 'hello2' }, { group: 'z', name: 'hello3' }, { group: 'x&apo ...

Angular forms with bootstrap can utilize the 'is-invalid' and 'is-valid' classes for added validation features

Consider a scenario where I have a small form and am using a reactive approach. For instance, there are two input fields: ... <input formControlName="name" name="name" type="text" class="form-control"> <input formControlName="amount" name="amount ...

When creating a Line chart in TypeScript of type time, values for the x-axis cannot be strings

I'm currently utilizing chart.js along with these libraries/versions in my Vite/React TypeScript project: chart.js: 4.3.0 react-chartjs-2: 5.2.0 chartjs-adapter-date-fns: 3.0.0 chartjs-plugin-datalabels: 2.2.0 I'm facing a dilemma as I aim to u ...

Is it possible to incorporate an interface with a named function in TypeScript (function declaration)?

Just dipping my toes into Typescript and experimenting with interfaces for my functions: interface StringFunction { (arg1: string): string } I managed to associate this interface with a function by declaring it as a variable: let testFunction: Strin ...

Having trouble running an Angular project using ng serve command?

When I try to run my angular template using the "ng serve" command, it doesn't work. Here is the code from my angular-cli.json: https://i.sstatic.net/lQ5Ma.png ...

Encountering TypeScript error TS2339 while trying to utilize a method from a different class within an event handler and binding the current

My development setup includes a service called DomService for all DOM manipulation tasks. Additionally, I have another service called ModalService that handles modal functionality. Within the ModalService, there are some events being bound, with a method ...

Can I implement react-router's useHistory() or React's useState method alongside withFormik?

Utilizing withFormik in my registration form. const RegistrationContainer = compose<InnerProps, OuterProps>( withFormik<InnerProps, RegistrationValues>({ mapPropsToValues: () => RegistrationSchema.cast(), validationSchema: Registra ...

Encountered an unexpected conclusion of JSON data during parsing the following section" Issue: npm install -g@angular/cli

I keep getting an error message every time I attempt to install Angular using the command npm install -g @angular/cli PS C:\Users\admin\Desktop\sonal> npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing ne ...

What advantages does using 'async' offer for TypeScript functions that already have a Promise return type?

Is there any advantage to declaring a TypeScript function as async if the return type is already a promise? It seems like both methods achieve the same result: function foo(): Promise<Bar> { } //vs async function foo(): Bar { } //Or even async fu ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Navigating a page without embedding the URL in react-router-dom

In my application, I am utilizing react-router-dom v5 for routing purposes. Occasionally, I come across routes similar to the following: checkup/step-1/:id checkup/step-2/:id checkup/step-3/:id For instance, when I find myself at checkup/step-1/:id, I int ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

What is preventing me from assigning the HttpClient result to a class property?

I've hit a major roadblock with this issue. Despite scouring the internet and spending hours on Stack Overflow trying to understand HttpClient, I'm still not making any progress. The task at hand involves fetching data from a REST endpoint using ...

Tips for resolving the issue: Encountered an unexpected token < when parsing JSON data at position 0 using the JSON.parse function

I encountered an error when working on the code mentioned in this post. After removing .json() from response.json() in my code snippet below, the error message changed: return this.http.post('http://localhost:3000/sign-up', body, {headers: head ...