Encountering an error message of "undefined" while attempting to append elements

Every time a user clicks the button, I need to append a value inside the sample array. Take a look at the code snippet below:

sample_apps.json:

{
     "user": {
        "userId": "maxwell",
        "sample": [

        ]
    }
}

app.component.ts:

import { Component } from "@angular/core";
import { OnInit } from "@angular/core";
import { ObservableArray } from "tns-core-modules/data/observable-array/observable-array";
import { AppService } from "~/app.service";
import { Sample } from "~/sample";

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html",
})

export class AppComponent implements OnInit {

    public obsArr: ObservableArray<Sample> = new ObservableArray<Sample>();


    constructor(private samService: AppService) {

    }

    ngOnInit(): void {

        this.obsArr = this.samService.sampleApps();



    }
    public addSample() {
        console.log("Adding Value");

       this.obsArr[0].samArr.push(3);
       for (let i = 0; i < this.obsArr.length; i++) {
        console.log("Get(" + i + ")", this.obsArr.getItem(i));
    }
    }

}

app.component.html:

<StackLayout>
<Button text="Add Sample" (tap)="addSample()"></Button>
</StackLayout> 

app.service.ts:

import { Injectable } from "@angular/core";
import { Sample } from "~/sample";
import { ObservableArray } from "tns-core-modules/data/observable-array/observable-array";
var samJsonData = require("~/sample_apps.json");

@Injectable()
export class AppService {

    public sampleApps(): ObservableArray<Sample> {

        console.log("SampleData", JSON.stringify(samJsonData));

        var sampleArrayList: ObservableArray<Sample> = new ObservableArray<Sample>();

         let sample : Sample = new Sample();
         sample.sampleUserId = samJsonData.user.userId;
         sample.samArr = samJsonData.user.sample;
         sampleArrayList.push(sample);

        return sampleArrayList;
    }

}

Sample.ts:

  import { ObservableArray } from "tns-core-modules/data/observable-array/observable-array";


export class Sample{

    sampleUserId : number;

    samArr: ObservableArray<any> = new ObservableArray<any>();;    
}

Encountering runtime error:

CONSOLE ERROR [native code]: ERROR TypeError: undefined is not an object (evaluating 'this.obsArr[0].samArr')

Expected outcome:

When the user clicks on the Add Sample button, the expected output should be as follows:

{
     "user": {
        "userId": "maxwell",
        "sample": [
           12
        ]
    }
}

Every time the user clicks the button, a number should be added to the sample array.

Answer №1

I made the following modification:

this.obsArr[0].samArr.push(3);

was changed to this:

this.obsArr.getItem(0).samArr.push(3);

This resolved the issue at hand.

As a result, I now see the desired outcome in the console:

 Get(0) {
"samArr": [
3
],
"sampleUserId": "maxwell"
}

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 causes the node_modules folder to become corrupted when publishing an AspNetCore2 project with Visual Studio?

During the development of my AspNetCore project using Kendo, Angular5, and AspNet Mvc, everything was running smoothly. However, when trying to publish the project, I encountered a strange issue where it breaks. https://i.sstatic.net/2xQ1Q.png I then cam ...

Populating a PrimeNG data grid using an array

I am currently facing a challenge while working with Angular and PrimeNG. I am new to this technology stack and trying to populate a table, but I seem to be missing something as there are no errors in the console. Here is the code snippet that I am struggl ...

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Assigning string properties to different types

I have numerous data types, each with a common property called dataType, and I am currently mapping each one to that specific value: interface GroupData { dataType: "group"; name: string; people: PersonData[]; } interface PersonData ...

Guide to obscuring all instances of a particular subsequence within a <p> tag

I am currently developing a project in Angular that showcases short texts. Within these texts, I aim to blur out specific substrings every time they appear. For example: Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hop ...

Exploring the functionality of the Typescript Parameters<> utility type within a generic function

I am facing a situation where I have the following class structure: class MyTestClass { getValue<T>(group: string, defaultVal: T): T {} } I want to use the Parameters value in order to simplify unit testing for this class (using a slightly contriv ...

Submit file in Cypress while hiding input[type="file"] from DOM

Currently, I am conducting end-to-end testing on an Angular project that utilizes Ant Design (NG-ZORRO). In this project, there is a button with the class nz-button that, when clicked, opens the file explorer just like an input type="file" element would. W ...

Incorporating JSON data into a reactive form group with nested objects and form arrays within nested components in Angular 13

After receiving JSON data from the backend and converting it into my model classes (which include nested classes and arrays), I encountered an issue while trying to create a reactive FormGroup by initializing it with my model class. The problem arose when ...

The Child Component encountered difficulties in connecting to the EventEmitter via the service

In the code snippet below, we have the Subscribing Component "pop-list.component.ts" : import { Component, OnInit } from '@angular/core'; import { ChildCommService } from '../child-comm.service'; @Component({ selector: 'app-pop- ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

Utilizing TypeScript's conditional return type with an object as a parameter, and incorporating default values

Is it possible to create a function where the return type is determined by a string, with some additional complexities involved? I'm looking to achieve the following: The parameter is contained within an object The parameter is optional The object it ...

Is there a method for creating TypeScript definitions that generates members dynamically?

While I'm not completely satisfied with the title of this question, I struggled to come up with something better at the moment. I have a feeling that what I am looking for may not be supported, but I am willing to be proven wrong! Currently, I am wo ...

Accessing component variables within an event in Angular 2 (dealing with scope problems)

I am currently facing an issue with scoping in my component click event. Specifically, I need to access private variables within the component, but the keyword this now refers to the event scope rather than the component's. This has led to an error wh ...

The npm package is unable to be imported

I've been working on a TypeScript project and wanted to incorporate the following library: https://github.com/Simonwep/pickr According to the project instructions, I have performed the following steps: import '@simonwep/pickr/dist/themes/nano.m ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...

Secondary Electron window not properly receiving IPC messages

While developing my TypeScript code that is linked to the HTML being executed by my application, I encountered an issue with creating a new window for my settings. It seems that the preloaded script is loaded onto the new window upon opening, but the windo ...

Unable to import library in Angular framework

I'm currently in the process of setting up js-beautify, which can be found at https://www.npmjs.com/package/js-beautify I installed it using the command npm install js-beautify --save Next, I added the import to my app.component.ts file The documen ...

"Integrating Orgchart with Typescript in Angular4: A Step-by-Step

mxResources.loadDefaultBundle = false; var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) || mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage); // Ensures synchronous requests are handled properly ...