How to Delete an Item from an Array in BehaviorSubject Using Angular/Typescript

I have encountered an issue while trying to delete a specific element from my array upon user click. Instead of removing the intended item only, it deletes all elements in the array. I attempted to use splice method on the dataService object, but I'm facing an error that says "Property 'splice' does not exist on type 'Observable< any>'". My goal is to remove just one element from the dataService based on the Object passed from the HTML. Any advice or suggestions would be highly appreciated! footer.component.ts

export class FooterComponent {
  nominations = [];
  constructor(private dataService: DataService) {
    this.dataService.currentNoms.subscribe(noms => {this.nominations.push(noms);});
  }
  ngOnInit(): void{
    
  }
  remove(nom: Object): any{
    this.nominations.splice(this.nominations.indexOf(nom), 1);
    console.log(nom);
    console.log(this.nominations);      
  }

}

footer.component.html

<div class="nominationsDisplay">
    <div id="nominations" *ngFor="let nom of nominations[0]">
        <img src={{nom.Poster}}/>
        <button class="removeBtns" type="submit" (click)="remove(nom)">Remove</button>
    </div>
</div>

data.service.ts

export class DataService {

  private finalNoms = new BehaviorSubject<any>([]);
  currentNoms = this.finalNoms.asObservable();

  constructor() { }

  addNominations(nom: Object){
    this.finalNoms.next(nom);
  }

}

Answer №1

You might want to consider this alternative approach:

footer.component.html

<div class="nominationsDisplay">
    <div id="nominations" *ngFor="let nom of nominations[0]; let i = index">
        <img src={{nom.Poster}}/>
        <button class="removeBtns" type="submit" (click)="remove(i)">Remove</button>
    </div>
</div>

TS File

remove(index: number): any{
    this.nominations.splice(index, 1);
    console.log(nom);
    console.log(this.nominations);      
  }

I utilized the index in the button click event to splice the array. Give it a try and observe the results.

Answer №2

To eliminate an item from your service.ts, simply follow these steps:

export class DataService {

  private nomineesList = new BehaviorSubject<any>([]);
  currentNominees = this.nomineesList.asObservable();

  constructor() { }

  addNominee(nom: Object){
    this.nomineesList.next(nom);
  }

  removeNominee(nom: Object) {
    const updatedArray = [...this.nomineesList.value];
    updatedArray.splice(this.nominees.indexOf(nom), 1);
    this.nomineesList.next(updatedArray)
  }

}

In the FooterComponent.ts

  delete(nom: Object): any{
    this.dataService.removeNominee(nom)     
  }

All subscribers will now be informed of the modification made.

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

Encountering issues passing the --aot and --prod flags to the ng build command

I'm having trouble passing flags to ng build. Here is the line of code I have: "build:aot:prod": "node --max_old_space_size=8092 ./node_modules/@angular/cli/bin/ng build --aot --prod" However, it seems to only run ng build without the flags. What co ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Having trouble removing or updating Angular Cli on a MAC device

Struggling with uninstalling angular cli on mac. npm remove -g @angular/cli ...

Issues resolving the signature of a parameter in a Typescript decorator within vscode

I encountered an error while attempting to decorate a class in my NestJS service. The Typescript code compiles without any issues, but I am facing this problem only in VSCode. Unable to resolve signature of parameter decorator when called as an expression ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

Changing Ionic Column Widths Based on Content Length

In my dynamic ionic 2 grid system, I am facing a layout issue. <div> <ion-row> <ion-col > ; <ion-card-header class="card-header"> {{hunt.title}} </ion-card-header> </ion-col> <ion-col *ngIf="!hunt. ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

Extracting and transforming an array into a list with the desired outcome

Looking for a way to flatten the array below into a single line array using Typescript/JavaScript? Student: any = [ { "id": "1", "name": "Jhon", "Marks": { "Math": "90", "English": "80", "Science": "70" } }, { "id": "2", "name": "Peter", "Marks": { "M ...

Angular2+ test case indicating lack of NgControl provider

I've been facing an issue while testing an angular component with multiple dependencies. The test case fails with the error: "No Provider for NgControl". Here's the detailed error message: Chrome 66.0.3359 (Mac OS X 10.13.4) configurator compone ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

Encountering an issue with the constructor function type for @types/tapable/index

Everything was running smoothly on my production website until I decided to run the "npm install" command on the server, followed by the "npm run build:prod" command. Unfortunately, I encountered the following error: ERROR in [at-loader] node_modules/@typ ...

An issue has occurred: changes.forEach does not function as expected

Encountered an issue while attempting to retrieve data from Firestore using Angular/Ionic. PizzaProvider.ts getAllPizzas() { return this._afs.collection<Pizzas>('pizzas', ref => ref); } pizzas-list.ts pizzas: Observable<any[]& ...

Challenges arise in communicating between parents and children in Angular 6

I seem to be encountering an issue with parent/child communication in Angular 6. The code appears to be functioning correctly, but I am running into an error in Karma. Here is the specific error message: Failed: Template parse errors: Can't bind to & ...

What does the concept of "signaling intent" truly signify in relation to TypeScript's read-only properties?

Currently diving into the chapter on objects in the TypeScript Handbook. The handbook highlights the significance of managing expectations when using the readonly properties. Here's a key excerpt: It’s crucial to clarify what readonly truly signif ...

Encountered an unexpected import token in Angular2 (SystemJS)

i am trying to find a solution for this issue in my Angular2 project. I encountered an error and need assistance: `"(SystemJS) Unexpected token import SyntaxError: Unexpected token import at Object.eval (http://....../app.module.js:14:25) at eval (h ...

The `staticAlert` property in the constructor.ts file does not have an initializer and is not explicitly assigned

import { Component, OnInit, ViewChild } from '@angular/core'; import {Subject} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {NgbAlert} from '@ng-bootstrap/ng-bootstrap'; @Component({ selecto ...