Getting undefined error when trying to add array

Issue

When user click on button, I have to add the value inside sample array. Below i have posted the code:

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("Addding 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>();;    
}

Getting runtime error:

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

Expected output:

when user click on Add Sample button, i have been expected output like below:

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

When ever user click on button, number has to be added into that sample array.

Solution

I changed:

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

to this:

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

to solve this issue.

Now i got my expected result in console:

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

Answered By – Steve

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.