Retrieving an object from an ObservableArray in a Nativescript application

Within my service class, I have an array of quests defined in the following manner:

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

quests: ObservableArray<Quest>;

To add quests to the array, I use the following code:

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

In a different class, I subscribe to change events of this array:

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

Although I can see my data inside the ChangedData object in the log, I am struggling to cast it back to my object.

Is there a way to accomplish this successfully?

Thank you.

Answer №1

After some troubleshooting, I came across a helpful solution for your issue here. The problem lies with the typings, as they do not display the required properties. To overcome this, simply assign the type any. Below are the necessary steps to resolve the issue:

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

Upon testing by adding a dummy object, I came across the following result. Pay attention to the index property for accessing the newly added property.

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

Here is the output obtained:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for using the pipe to convert currency rates to a specific currency type?

I am working on a project where I need to display currency rates in the selected currency type all over the page. I have a dropdown with various currency types and want to dynamically update the rates based on the selected currency. After some research, I ...

Modeling a potentially empty array in Typescript can be achieved by implementing specific interface definitions

Here is the current situation: type A = { b: string, c: number } I have an object that I will receive from an API, which could be either A[] or [] As of now, when I attempt to use it, const apiData: A[] || [] const b = apiData[0].a // I expected this to ...

What direction does Angular2 animation rotate in?

In my Angular2 application, I am trying to create a menu icon that rotates clockwise when shown. The desired animation is for it to rotate from -360 degrees to -180 degrees when displayed and from -180 degrees to 0 degrees when hidden. Currently, the anim ...

Creating horizontal cards with Angular MaterialWould you like to learn how to design

I need help converting these vertical cards into horizontal cards. Currently, I am utilizing the Angular Material Cards component. While I can successfully create cards in a vertical layout, my goal is to arrange them horizontally. Below is the code sni ...

Retrieve a collection within AngularFire that includes a subquery

I have the following function getParticipations( meetingId: string ): Observable<Participation[]> { return this.meetingCollection .doc(meetingId) .collection<ParticipationDto>('participations') .snapshotCh ...

There seems to be a compatibility issue between Angular 16 and Bootstrap 5 styling

In my angular.json, I have defined my styles in the following way: "styles": [ { "input": "node_modules/bootstrap/dist/css/bootstrap.min.css", "bundleName": "ltrCSS" }, { "input": "node_mod ...

Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance. Currently, I am retrieving data from the back end that has the following structure: { "Airports": { "BCN": { "Arrivals": [ ...

Creating a personalized tooltip in Angular for a bubble chart with ApexCharts

I'm currently working on customizing the tooltip for a bubble chart using the ApexCharts library. Here is the link to my project. ...

Angular Material - truncating selected text in a list

I'm having trouble implementing the Angular Material list with checkboxes, where the text needs to be truncated instead of word-wrapped due to limited UI space. I have modified an example on the Angular Material site to demonstrate the issue. The text ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Ways to dynamically update the state of a mat-button-toggle-group programmatically

I'm currently working on implementing a confirmation dialog to change the state of MatButtonToggleGroup. However, I am facing an issue where I need to prevent the default behavior unless I revert to the previous state upon cancellation. Here's t ...

Open new tab for Angular OAuth2 OIDC login process

Currently, I am incorporating the authorization code flow using angular-oauth2-oidc in my Angular application. It is a fairly straightforward process. However, I would like to have the ability for the login flow to open in a new tab when the login button ...

The SonarQube code coverage differs from that of Jest coverage

I'm struggling to grasp why SonarQube and Jest coverage results differ so significantly. SonarQube coverage resultshttps://i.sstatic.net/dodGi.png Jest coverage https://i.sstatic.net/uYKmt.png https://i.sstatic.net/rakzw.png https://i.sstatic.net/ ...

Maintaining a fixed header that remains visible while scrolling through a dropdown menu in Angular

In my application, I have a mat-select widget that displays a list of options. When scrolling within the list, I find it difficult to keep track of all the options. I am looking to enhance the user experience by adding a fixed header at the top of the opt ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

Express and Angular 2 Integration in package.json

Hello, I am new to learning Angular 2 and have a better understanding of Express. One thing that is confusing me is the package.json file, particularly the "start" part. Here is my package.json when I only had Express installed: { "name": "Whatever", ...

Position the mat-icon button in the top right corner for the close button

I'm struggling with positioning my close icon button at the top right corner of my dialog box. Here is my app-iconbutton component: <button mat-icon-button class="iconbutton" [ngStyle]="{ 'background-color': back ...

Angular progress bar with intermittent breaks

Currently developing an Angular application and looking to implement a progress bar similar to the one displayed in the linked images. https://i.sstatic.net/5doDu.png https://i.sstatic.net/SP2it.png Although there are multiple progress bars available on ...