Developing Placeholder Model in Angular

I am currently working on creating a sample model in Angular to fetch data from the backend. However, I am encountering an error related to arrays.

abc.ts

export class abc {

    date: Date;
    time: string;
    ABC_Info: [{
            item: string,
            quantity: number,
            a: number
        },
        {
            item: string,
            quantity: number,
            a: number
        }
    ]

    constructor(date: Date, time: string, item: string, quantity: number, a: number) {
        this.meal_time = meal_time;
        this.date = date;
        this.time = time;

        this.ABC_Info[0].item = item;
        this.ABC_Info[0].quantity = quantity;
        this.ABC_Info[0].carbs = a;

        this.ABC_Info[1].item = item;
        this.ABC_Info[1].quantity = quantity;
        this.ABC_Info[1].carbs = a;

    }
}

abc.service.ts

import { abc} from './models/abc';

getABCs(start ? : moment.Moment, end ? : moment.Moment): Observable < abc[] > {
    let params = new HttpParams();

    if (start) {
        params = params.append('start', start.toISOString());
    }

    if (end) {
        params = params.append('end', end.toISOString());
    }
    return this.baseService.getParams('/api/abc/getAll', params)
        .pipe(
            map(res => res as Object[] || []),
            map(bolus => bolus.map(k => new abc(
                    new Date(k['date']),
                    k['time'],
                    k['item'],
                    k['quantity'],
                    k['a']))

            )
        )
}

Error in browser console

ERROR TypeError: Cannot read property '0' of undefined at new Bolus(abc.ts: 39) at abc.service.ts: 33 at Array.map( < anonymous > ) at MapSubscriber.project(carb.service.ts: 33) at MapSubscriber.push.. / node_modules / rxjs / _esm5 / internal / operators / map.js.MapSubscriber._next(map.js: 35) at MapSubscriber.push.. / node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next(Subscriber.js: 54) at MapSubscriber.push.. / node_modules / rxjs / _esm5 / internal / operators / map.js.MapSubscriber._next(map.js: 41) at MapSubscriber.push.. / node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next(Subscriber.js: 54) at MergeMapSubscriber.push.. / node_modules / rxjs / _esm5 / internal / operators / mergeMap.js.MergeMapSubscriber.notifyNext(mergeMap.js: 84) at InnerSubscriber.push.. / node_modules / rxjs / _esm5 / internal / InnerSubscriber.js.InnerSubscriber._next(InnerSubscriber.js: 15)

Answer №1

Here is an example of defining a model:

export interface Xyz {
  date: Date;
  time: string;
  XYZ_Details: {item: string, quantity: number, x: number}[]
}

Next, in your API service:

getXyz(): Observable<Xyz> {
  return this.http.get('some api').pipe(map(res => res.json)); // If using Angular version below 6, remove pipe
}

Answer №2

Have you considered this approach: Declaring an Array of Objects in Angular 2

It appears that you may be attempting to specify a type for your array while also making space for two objects, which is not the correct method (refer to the provided link).

The error you are encountering likely stems from your array not being initialized when trying to access the index 0 (verify this by using a console log with a breakpoint - it will show that your array is undefined).

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 personalizing a DaisyUI theme in Tailwind with TypeScript?

I am trying to tailor an existing DaisyUI theme using my tailwind.config.ts file for my Next.js project. Although the DaisyUI documentation only provides examples in JavaScript (text), I want to customize it within my TypeScript environment. Below is a s ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Ng2-NoUISlider displaying consistent range values

I'm facing an issue with implementing multiple sliders on a single page where each slider should have different range values. Here is a snippet of my HTML: <div *ngFor="let property of comepleteFilters"> <h5>{{property.pro ...

Is the input URL modified by the Angular HttpClientModule's GET request?

I am currently using an Angular service to make calls to a Node.js server in order to fetch data. Here is a snippet of my code: constructor(private http: HttpClient){ } getPersonData(): Observable<person[]> { //return this.http.get<person ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Exploring the capabilities of the hardware camera in Angular 2

Struggling to implement the tutorial in Angular2. The challenge lies in making navigator.mediaDevices.getUserMedia function properly. The error message indicates that mediaDevices is not recognized on type 'navigator'. Refer to the media capture ...

Ensuring the presence of TypeScript variables

Take a look at this code snippet: let str: string | null; function print(msg: string) { console.log(msg); } print(str); When running this code, the typescript compiler correctly identifies the error, stating that Argument of type 'string | nu ...

Tips on accessing fields for union types that are passed to a function in TypeScript

I'm currently diving into the world of TypeScript, teaching myself by putting my newfound knowledge into practice. Below is the code I'm working on, but I've hit a roadblock trying to access the fields of the type passed to the function. C ...

Oops! There seems to be a mistake: Unable to access the 'helpers' property of an undefined object

Click here to see my code import { OnInit } from '@angular/core'; import { HelpersService } from 'src/app/helpers.service'; @Component({ selector: 'app-system-maintenance', templateUrl: './system-maintenance.page.htm ...

assign an exclamation mark as a prop value within a React component

Recently, I came across this code snippet and it left me puzzled. I understand that `list` is an array of objects, but I'm unsure about the significance of the exclamation mark (`!`). How will it impact my approach in handling the MyComponent componen ...

"Troubleshooting problem with Angular component styling and managing overflow within a

Creating a basic component setup like this: .time { font-size: 100px; } .seconds { font-size: 80px; } <div class="time">{{ now | date: "HH:mm" }}</div> <div class="seconds">{{ now | date: "ss" }}</div> Showcased in the attac ...

Typescript - Conditional imports

When working with the moment-timezone module, one issue that arises is receiving a warning if it is included multiple times. In my specific case, I have a module that necessitates the use of this timezone functionality. Since I am unsure whether or not the ...

Adjusting the line width and incorporating arrow points into AxesHelper in Three.js

I have successfully implemented axes using AxesHelper https://i.sstatic.net/gYCKW.png Currently, I am looking to enhance the width of the axes lines and incorporate arrow points. Since I am new to three.js, I could really use some guidance on how to ach ...

Develop custom Angular applications using the CLI by creating a new schematic in Nx and setting up the Angular configuration

Currently, I am working within a nrwl/nx monorepo where my applications have custom configurations set in the angular.json file. One specific customization is the output path. Now, I am looking to create my own schematic that can configure my project accor ...

The ongoing ESLint conundrum: Balancing between "Unused variable" and "Unknown type" errors when utilizing imports for type annotations

I've encountered a linting issue and I need some guidance on how to resolve it. Here's the scenario - when running $ yarn lint -v yarn run v1.22.4 $ eslint . -v v6.8.0 With plugins vue and @typescript-eslint, I have the following code in a .ts ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

Angular2/4 preflight request encountered an invalid response which resulted in a redirect

In my project, I am utilizing angular4 for the frontend and a spring boot application for the backend. The communication between the frontend and BFF (backend for frontend) is done via RESTful requests. When the frontend sends a POST request to the backen ...