当用户单击按钮时,我必须将值添加到示例数组中。我在下面发布了代码:
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>();;
}
遇到运行时错误:
控制台错误[本机代码]:错误TypeError:未定义不是 对象(评估“ this.obsArr [0] .samArr”)
预期输出:
当用户单击“添加样本”按钮时,预期输出如下:
{
"user": {
"userId": "maxwell",
"sample": [
12
]
}
}
每当用户单击按钮时,都必须将数字添加到该示例数组中。
答案 0 :(得分:1)
我更改了:
this.obsArr[0].samArr.push(3);
对此:
this.obsArr.getItem(0).samArr.push(3);
解决此问题。
现在我在控制台中得到了预期的结果:
Get(0) {
"samArr": [
3
],
"sampleUserId": "maxwell"
}