The RadListView in Angular Nativescript fails to update when triggered from a different page

My RadListView is populated with data from an http request:

<RadListView #listView separatorColor="transparent"
        pullToRefresh="true" (pullToRefreshInitiated)="refreshFavorites($event);" *ngIf="filteredItems && filteredItems.length; else noItems" row="2"
            [items]="filteredItems" marginTop="-100" (touch)="dismissKeyboard($event)">
    <ng-template let-item="item" let-i="index">
        <GridLayout columns="10,*,10">
            <GridLayout *ngIf="item" (tap)="goToInner(item)" [nsRouterLink]="['../favorite', item.ean]" pageTransition="slide"  shadow='6' cornerRadius='5' col="1" columns="*,auto" class="p-8 m-b-8 m-x-8" borderRadius="8"
            backgroundColor="white">
                <GridLayout class="favorite-card" col="0" columns="150,*,auto" rows="auto,auto,auto">
                    <Image col="0" rowSpan="3" class="thumbnail m-r-12" stretch="aspectFit" *ngIf="item.images"
                        [src]="item.images.large.url"></Image>
                        <StackLayout col="1" row="1" verticalAlingment="center">
                                <Label  class="h3 title m-t-4" marginBottom="0" textWrap="true" maxLines="2" [text]="item.productTitle"></Label>
                                <Label class="h5 caption" [text]="item.manufacturer"></Label>
                        </StackLayout>
                </GridLayout>
                <StackLayout col="1" verticalAlignment="top" (tap)="removeFromFavorites(item, i)">
                        <Image horizontalAlignment="right" src="~/images/favorite-active.png" width="20" height="20"></Image>
                </StackLayout>
            </GridLayout>
        </GridLayout>
    </ng-template>
</RadListView>

If I want to update the RadListView in inner.component and add an item to it:

filteredItems : ObservableArray<Observable> = new ObservableArray([]);
public update(item){
    this.filteredItems.push(item)
}

However, when I try to add an item from another component, the RadListView does not get updated:

providers: [InnerComponent],    
constructor(private inner: InnerComponent){}
addItem(item){
    this.inner.update(item)
}

I am puzzled as to why my RadListView does not update after calling a function from another component, even though the items are identical in both components.

Answer №1

To implement the functionality, you will need to create a service and utilize BehaviorSubject as demonstrated in this illustrative guide. It is generally not recommended to inject components using providers. Within your service.ts file:

filteredItems;



public filteredItemsSubsSource = new BehaviorSubject(new ObservableArray<item>());
public filteredItemsSubs = this.filteredItemsSubsSource.asObservable();

addItem(item){
    this.filteredItems.push(item);
    this.filteredItemsSubsSource.next(filteredItems);
}

Then, in another component, inject the service and subscribe:

providers: [Service],    
constructor(private _service: Service){}

addItem(item){
    this._service.addItem(item);
}

Additionally,

this._service.filteredItemsSubs.subscribe(
            (filteredItems) => {
                this.filteredItems= filteredItems;

            }
        );

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

Using Typescript, pass a Sequelize model as a property in NodeJS

Currently in the midst of a project using Node, Typescript, and Sequelize. I'm working on defining a generic controller that needs to have specific functionality: class Controller { Schema: <Sequelize-Model>; constructor(schema: <Sequel ...

Integrating Solace Node.js API with Webpack

I am currently working on an Angular2 TypeScript web application that has been built using webpack. My goal is to integrate solclientjs into the project, but I keep encountering the error displayed below: solclientjs-exports.js:34 Uncaught Error: Cannot f ...

I have encountered a problem where I am trying to post a URL using a REST API call. This functionality was working perfectly fine in Angular 1.6, but I am facing

When trying to post a URL with Angular 7 to the server, I encountered an error stating "blocked by CORS policy," although it worked fine in Angular 1.6. The issue is related to CORS policy blocking access to XMLHttpRequest. The response to preflight reque ...

Maintain Angular Dropdown Menu Open Across Page Refresh

I am currently working on an HTML/Typescript view that is connected to a SQL Database. Whenever there are changes made to the database, the entire webpage reloads. The issue we are facing is that we have dropdown menus on the page that clients want to rema ...

Troubleshoot: Angular hide/show feature malfunctioning

I am facing an issue where clicking on one parent element causes all parent elements to show or hide their child elements accordingly. I am relatively new to Angular 2 and would appreciate any recommendations. Below, you can see the code for the component ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

How to Use Exceljs to Extract Date Data in Specific Cell Formatting

While working on a project using Nest, I encountered an issue when reading a Date value from columns in an excel file using the exceljs package. Instead of getting the Date data type in the correct format, I am receiving a number as the output. Here is th ...

What is the proper way to utilize the component prop when working with custom components?

I'm currently experimenting with using the Link component from react-router along with my customized button component. However, I seem to be encountering an issue that I can't quite figure out: <Button component={Link} to="/"> "This works" ...

What is the proper way to specify type hints for a Map with keys being classes and values being instances of those classes?

I possess a map where the keys represent different classes and their corresponding values are instances of those classes. // JavaScript code class A {}; class B {}; const map = new Map(); map.set(A, new A); map.set(B, new B); What would be the correct w ...

Accessing Parent Component's Route Parameters in Child Component in Angular 5

Here we have the add-new-folder.component, which functions as a child component of the folder.component. When routing to the add-new-folder.component from the parent folder.component, I need to access the userid parameter of the parent component in its chi ...

The import of my library using package.json exports is failing due to TypeScript compilation errors

I am currently developing a JavaScript library that I want to make importable via script tags, ES6 imports, and traditional Node requires, with or without TypeScript or any build systems. However, I am facing challenges in achieving this. Within my packag ...

Configuring VS Code's "tasks.json" file to compile all .ts files can be done by following these steps

Apologies if this question has been asked before, but could someone please redirect me to the relevant thread if so. I am wondering if it is possible to set up VS Code's "tasks.json" to automatically compile all .ts files within a folder. Currently, I ...

The error message in React JS Typescript states: "Cannot assign a string to a parameter that requires a SetStateAction<number>"

Hey there! I encountered this error: Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'. Here is a snippet of my code where the error occurred: . . . const[ idPadre, setIdPadre ] = useState& ...

Best practices for managing types with ES6 Map<K,V> functions in Typescript

My current setup involves a class structured like this: export class Broker<T> implements BrokerContract<T> { topicToSubscribersMap: Map<string, Set<Subscriber<T>>>; . ...

What is the best method for setting a dash as the default value in a template?

My HTML code in Angular 8 includes the following: <span>{{post.category || '-'}}</span> If post.category is empty, a dash is shown as expected. However, I am facing two other situations: <span>{{post.createdAt || '-&apo ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

Update the input for a component within the ngOnChanges method, and ensure that the OnPush change

I've encountered an issue with my Angular 6 application: The Dilemma Imagine I have two components: parent and child. The child component has two inputs. When one input changes, the child emits something to the parent within the ngOnChanges() lifec ...

Error: Value Loop Detected in AngularFire Document ID

I encountered a "Cyclic Object Value" Error while working on an Angular Project with AngularFire. As a beginner with Firebase, I haven't been able to find a straightforward solution to this issue. The error arises when I query a collection in my Fire ...

Integrating CKAN with Angular framework

I've been working on incorporating front end pages in Angular into my ckan extension. However, I'm facing difficulties due to the Jinja templating system used in ckan. I am unsure if this is possible or supported with any version of Angular. If ...

The functionality of Layout.tsx is inconsistent across various pages

I'm having trouble with the console.log() code to display the page path only showing up in the "pages.tsx" file (src/app/pages.tsx) and not appearing in the console for other files located in (src/page/Login). Here is the code from layout.tsx: ' ...