首页 文章

在Nativescript中获取ObservableArray对象

提问于
浏览
0

我有一个服务类,有一系列的任务,如下所示:

import { ObservableArray, ChangedData } from 'tns-core-modules/data/observable-array/observable-array';

quests: ObservableArray<Quest>;

我可以像这样将任务推入数组:

let quest = new Quest(data.key, data.value["name"], data.value["description");
this.quests.push(quest);

在另一个类中,我订阅了更改该数组的事件:

this.myService.quests.on(ObservableArray.changeEvent,(args:ChangedData<Quest>) => {
    console.log(args.object);
    let quest: Quest = args.object; // can not cast to quest
});

在日志中我可以看到我的数据在 ChangeData 内 . 但是我很可能没有把它归还给我的对象 .

我怎样才能做到这一点?

谢谢

1 回答

  • 2

    我为你找到了一个解决方案here . 问题是打字 . 它不显示您需要的属性 . 所以只需要输入类型 any 基本上你需要做以下事情:

    this.myService.quests.on(ObservableArray.changeEvent, (args: any) => {
      console.log(args.index);
      //the item which was added
      console.log(this.myService.quests.getItem(args.index));
      //now you can cast it
      let quest = <Quest>this.myService.quests.getItem(args.index);
      console.log(args.action); // Action (In this case "add")
    });
    

    当我试图添加测试对象时,我得到了这个 . 注意index属性 . 使用 index ,您将获得新添加的属性 .

    this.myService.quests.push({ name: 'test1' });
    this.myService.quests.push({ name: 'test2' });
    

    这是输出:

    JS: 0 //this is index
    JS: {
    JS:   "name": "test1"
    JS: }
    JS: add //this is the action
    JS: 1
    JS: {
    JS:   "name": "test2"
    JS: }
    JS: add
    

相关问题