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.