Exploring Array Iteration in a subscribe and ngOnInit Function

I'm facing a challenge where I need to iterate through an .subscribe() method placed inside an ngOnInit() method:

 ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => {
         this.books = listBooks
        var events: CalendarEvent[] = [
        {
          start: new Date(this.books[0].date_from_og), //loop instead of 0
          end: new Date(this.books[0].date_to_og),
          title: "" + this.books[0].device + "", 
          color: colors.yellow,
          actions: this.actions,
          resizable: {
          beforeStart: true,
          afterEnd: true
         },
         draggable: true
        }];
        this.events = events;
      },
      (err) => console.log(err)
    ); 

  }

I am trying to figure out how to loop through the books[ ] Array and populate every item into the events[ ] Array without any success so far.

Answer №1

To simplify the process, you can loop through the books array like this:

ngOnInit() {
  this.service
    .getEmployees()
    .subscribe(
    (bookList) => {
      this.books = bookList;
      this.events = this.books.map((item) => {
        return {
          start: new Date(item.date_from_og), // accessing current element directly in the iteration
          end: new Date(item.date_to_og),
          title: "" + item.device + "",
          color: colors.yellow,
          actions: this.actions,
          resizable: {
            beforeStart: true,
            afterEnd: true
          },
          draggable: true
        };
      });
    },
    (error) => console.log(error)
  );
}

Answer №2

Give this a shot:

this.library.forEach(item => {
  let entry = {
    begin: new Date(item.start_date),
    finish: new Date(item.end_date),
    name: "" + item.title + "",
    color: colors.blue,
    functions: this.functions,
    adjustable: {
      atBeginning: true,
      atEnd: true
    }
  }
  this.entries.push(entry)
});

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

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

Angular elements that function as self-validating form controls

I'm wondering if there's a more efficient approach to achieve this, as I believe there should be. Essentially, I have a component that I want to function as an independent form control. This control will always come with specific validation requi ...

Issue with NgRx Testing: Callback in subscribe method fails to update during testing

I am currently working on testing a component that is responsible for editing shopping list items. Upon first loading, the component receives state values through store.select, which are: editedIngredient: null, editedIngredientIndex: -1 Based on these ...

The 'google.maps' namespace does not export the 'MouseEvent' member after installing @agm/core and @types/google

When attempting to install @agm/core and @types/google maps, I encountered the following errors: node_modules/@angular/google-maps/map-polyline/map-polyline.d.ts:42:45 - error TS2694: Namespace 'google.maps' does not have an exp ...

The process of ensuring a component is able to watch for the router even when it is not within the router

I am facing an issue with setting v-if for an element to get a boolean value from a function when the router changes the URL. Here is the code snippet for my Header component: <template> <header class="wfm-header"> <div class=" ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly. The component in question is: @Component({ selector : 'default-actions', templateUrl : './default.actions.template.html&a ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

Tips for incorporating state properties into a component

Currently engrossed in a project revolving around state management for individual components utilizing Angular 7 and NGRX. The challenge at hand is to ensure scalability of the implementation, allowing multiple uses while maintaining independence. Thus fa ...

What is the best way to find a specific string within an array of strings?

I have a list of tasks as strings: todo=[ 'Get up', 'Brush my teeth', 'Go to work', 'Play games' ]; I am attempting to compare it with this: Template: <input (input)="checkArrays($event)" /> In my ...

CSS styles from Angular 2 components spilling outside of their boundaries

Check out the Plunker where I'm facing an issue. "If you comment out the styles in the ThirdComponent, you can see it affecting the parent and sibling components' styles." – adriancarriger (Special thanks to Adrian) Within my component, I am i ...

How can I make TypeScript's http.get Observable wait for the inline parameter to be returned?

I'm currently facing an issue with my http.get call in which I need one of the parameters (getUserToken) to be returned before the function is executed. However, I don't want to chain them together since the calling function getSomeData returns a ...

Utilizing the most recent HTTP response from the previous request in Angular 8

Currently working with angular 8 and facing an issue on my list page with filters. Whenever a filter value is changed, it triggers an http request. The problem arises when users start changing the filters too frequently, causing multiple api requests to be ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Is there a way to verify a user's login status?

Currently, I am working on an angular 13 project and incorporating @angular/fire 7 into my development process. I have developed a service with various functions for injection. Below is the code snippet: import { Injectable } from '@angular/core&apos ...

Angular Fails to Identify Chart.js Plugin as an Options Attribute

Encountering issues with using the 'dragData' plugin in Chart.js 2.9.3 within an Angular environment: https://github.com/chrispahm/chartjs-plugin-dragdata After importing the plugin: chartjs-plugin-dragdata, I added dragdata to the options as sh ...