0

I have a service class that has a array of quests like so:

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

quests: ObservableArray<Quest>;

I can push quests into the array like this:

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

In another class I subscribe to change events of that array:

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

In the log I can see that my data is inside the ChangeData. But I horribly fail to cast that back to my object.

How can I achieve that?

Thanks

6
  • have you tried let quest = <Quest> args.object; ? Commented Aug 28, 2018 at 5:25
  • Yes @DotNetDreamer I did Commented Aug 28, 2018 at 5:36
  • try the above and remove the typing from (args:ChangedData<Quest>) => make it (args) => Commented Aug 28, 2018 at 9:13
  • Nope, not working @DotNetDreamer Commented Aug 28, 2018 at 9:14
  • args if of type EventData its object property is of type element which raised the event. So you can't grab the Quest from its object. So you will be only notified by change detection. You can see this here docs.nativescript.org/core-concepts/events Commented Aug 28, 2018 at 9:24

1 Answer 1

3

i found a solution for you here. The problem is the typings. It doesn't show the properties that you need. So just make it of type any Essentially you need to do the following:

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

When i tried to add a test object, i got this. Notice the index property. Using index you will get the newly added property.

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

And here was the output:

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your effort, I'll try this later!
@NicoS.glad it helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.