Refresh an array prior to subscribing in Angular 2

When attempting to apply multiple filters in a quick session, I am encountering an issue where the previous data persists in the array alongside the new data. How can I effectively remove the previous data?

component.ts

ngOnInit() {
  this.vehicleAttribute = JSON.parse(sessionStorage.getItem('vehicleAttributes'));
  const data: ProductCatalogPostData = {
    vehicleModelAttributes: this.vehicleAttribute.vehicleModels[0].modelAttributes,
    role: 'vehicle owner',
    planType: this.planType
  };
  const page: ProductCatalogPostPagination = {
    page: this.pageNo
  };
  this.productCatalogService.compatibleProducts(data, page.page).subscribe(
    response => {
      for (let i = 0; i < response.products.length; i++) {
        this.lists.push(response.products[i]);
      }
      this.pageCount = response.totalCount;
    },
    error => {
      console.log(error);
    }
  );
}

In my filter function, I attempt to empty the list.

onSelectedChange($event) {
  this.lists = [];
  this.planType = $event[0]
  this.ngOnInit();
}

However, I am still seeing the previous subscribed data in addition to the new data. Any suggestions would be greatly appreciated.

Answer №1

To accomplish this task, utilize the do operator in the code snippet below:

this.productsService.findProducts(data, page.page)
  .do(result => {
       if(isEmpty(result)) {
          this.items = new Array();
       }
   })
  .subscribe(response => {
      for (let j = 0; j < response.products.length; j++) {
        this.items.push(response.products[j]);
      }
      this.totalPages = response.count;
    },error => {
      console.log(error);
    });

Answer №2

I'm not sure why you're looping through it, why not just do

this.list = response.items

Alternatively, if you have a specific reason for not doing it that way, you can duplicate the elements using

this.list = [].concat(response.items)

If you prefer to add all of them at once without clearing anything,

this.list.push(...response.items)

The last method is equivalent to:

Array.prototype.push.apply(this.list, response.items)

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 causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

Managing development environments and webpack configuration in Angular CLI 6.0.1

Within the angular.json file, there is a section that looks like this: "configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

The patchValue() function in FormGroup does not fire the input event

In my code, I have a FormGroup dedicated to credit card inputs. To format the inputs, I'm using a directive with the selector 'appCreditCardFormat'. Here's a simplified version: <input formControlName="cardNo" appC ...

The upcoming development server will exclusively deliver HTML content without scripts or assets, mirroring the setup of the standard create-next-app template

In an attempt to recreate the problem I am facing, I decided to start by setting up a new Next.js app template folder using the command npx create-next-app (Version 13.1.6==latest, all default options, Node v18.14.0==LTS). However, when I try to run the pr ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

Switching between various conditions

Here is a sample of my component: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'myApp-component', templateUrl: './myApp.component.html', styleUrls: ['./myApp.component.scss'] }) ex ...

Using child routes in eager loaded components can be achieved without making any changes to

In many tutorials, I have noticed that RouterModule.forChild(..) is commonly used for lazy loading. However, I am of the opinion that this forChild method can also be utilized for eager loading. Its advantage lies in the fact that routes can be configured ...

Refreshing the page causes TypeScript Redux to lose its state

custom/reducer/shoppingReducer.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { ShoppingReducerInitialState } from "../../types/reducer-types"; import { ProductItem, ShippingDetails } from "../../types/typ ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Encountering difficulties while attempting to set up ngx-doc-viewer in Angular 9

Having trouble installing ngx-doc-viewer in my Angular 9 project. Encountered some errors, here they are attached. Has anyone dealt with these issues before? or Recommend any other document viewer compatible with Angular 9. npm ERR! code ERESOLVE npm E ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

What is the process for integrating mobiscroll into an Angular project using a customized username?

After installing the mobiscroll trial in my angular project, I decided to reinstall it with a new username. Despite attempting to remove the library and using the command "mobiscroll config angular", I encountered an issue where it was still logging in w ...

Meteor - The dependency specified in [email protected] or [email protected] is unmet

I am facing an issue with my meteor project using angular2. When I try to install the package rxjs5.0.0-beta.11 using 'meteor npm install', it gives me the following message: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Encountering an "Invalid hook call error" while utilizing my custom library with styled-components

I recently developed my own custom UI tool using the styled-components library, integrating typescript and rollup for efficiency. One of the components I created looks like this: import styled from 'styled-components' export const MyUITest2 = s ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

What does the 'key' parameter represent in the s3.put_object() function?

Currently, I'm utilizing Boto in my project to upload artifacts to an s3 bucket. However, I am uncertain about the usage of the Key parameter within the put_object() method: client.put_object( Body=open(artefact, 'rb'), Bucket=buc ...

What are the new features for listening to events in Vue 3?

Currently, I am manually triggering an event: const emit = defineEmits<{ (e: 'update:modelValue', value: string | number): void }>() // [..] <input type="text" :value="modelValue" @input="emit(&apos ...