A guide on effectively utilizing BehaviorSubject for removing items from an array

Currently, I am working on an Angular 8 application that consists of two components with a child-parent relationship. It came to my notice that even after removing an item from the child component, the item remains visible in the parent component's list until the page is refreshed.

To address this issue, I have implemented a service called ItemListService:

export class ItemListService {
 _updateItemChanged = new Subject<any>();
 _removeItemChanged = new BehaviorSubject<any>([]);

  constructor() {}
}

Here is how I handle the item removal in the child component (item.ts):

openRemoveDialog() {
    const dialogRef = this.dialog.open(ItemRemoveDialogComponent, {
      width: '500px',
      height: '500px',
      data: {
        dossierId: this.dossier.id,
        item: this.item,
        attachments: this.item.attachments
      }
    });

    this.itemListService._removeItemChanged.next(this.item.title);

    dialogRef.afterClosed().subscribe(result => {
      if (result === true) {
        this.router.navigate(['/dossier', this.dossier.id]);

      }
    });
  }

In the parent component's view (view.ts), where the actual refresh needs to occur, I'm facing some challenges:



 ngOnInit(): void {
    this.show = !this.router.url.includes('/item/');

    this.itemlistService._updateItemChanged.subscribe(data => {
      const index = this.dossierItems.findIndex(a => a.id === data.id);
      this.dossierItems[index] = data;
    });

    this.itemlistService._removeItemChanged.subscribe(data => {
     // Unsure what logic to implement here

    });

I am seeking guidance on what changes need to be made to achieve the desired functionality.

Thank you for your assistance.

Additionally, here is the updated remove function:

remove() {
    this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
      .subscribe(() => {
        this.dialogRef.close(true);
        this.itemListService._removeItemChanged.next(true);
      }, (error) => {
        const processedErrors = this.errorProcessor.process(error);
        this.globalErrors = processedErrors.getGlobalValidationErrors();
    });
  }

And in the view.ts file, I have added the following:

 ngOnInit(): void {
  this.itemlistService._removeItemChanged.subscribe(update => update === true ? this.dossierItems : '');
}

Despite these updates, the list still fails to refresh automatically.

Answer №1

To trigger a screen update in Angular, it is essential to create a new reference to the array as shown below:

this.updatedItemsService.subscribe(data => { 
    // What should be filled in place of this.dossierItems.pop()?
    this.dossierItems = this.dossierItems.filter(e => e.title !== data);
});

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 most effective way to implement Promises within a For loop?

const wiki = require('wikijs').default; const { writeFileSync } = require("fs") const dates = require("./getDates") //December_23 for (let i = 0; i < dates.length; i++){ wiki() .page(dates[i]) .then(page => p ...

Navigating State as a Fresh Path in Ionic Framework using Angular UI-Router

I am currently using the Ionic Framework along with its AngularJS UI-Router and $stateProvider to manage different views within my application. However, I am facing challenges in specifying to the $stateProvider that I have multiple "Main Views", each of ...

Is it possible to execute Ajax insertions in the right sequence without relying on async:false?

My ASP.Net MVC page contains an AJAX form that allows users to submit data manually or copy large amounts of data for submission at once using JavaScript. @using (Ajax.BeginForm("action", "controller", new AjaxOptions { HttpMethod = "POST", ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

Issue with logging objects in an array within a for loop

I am having an issue with a JavaScript for-in loop. Why does console.log(user) display the number "0" when iterating through users? Is it indicating the index of the user object in the array? I would like to log each object individually... Thank you r ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...

Switch between two PHP files with a toggle feature using jQuery click event

Need help with toggling between two PHP files - cab.php and d3.php. Toggling within the same file works fine, but encountering issues when trying to toggle from one file to another. function botaod2mostraesconde() { $(".wrapd2").toggle(); $( ...

Forcing locale in Angular 2: A step-by-step guide

I recently developed a compact application with Angular2 and incorporated the currency pipe. I noticed that the currency is automatically formatted based on my browser's language. Is there a way for me to customize or override this default behavior? ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Monitor the x and y positions for platformer game interactions using only JavaScript and jQuery

I am currently working on a 2D platformer game as part of my college project alongside my friends. We are using jQuery and pure JS for development. So far, we have been able to move the character left and right using jQuery's animate function, and ena ...

"Using Nightwatch.js to Trigger a Click Event on a Text Link

My goal is to use Nightwatch for testing the login process by clicking on a log in text link. I came across this helpful article: How to click a link using link text in nightwatch.js. The article suggested using the following code: .useXpath() // ever ...

service.js was identified as registered, however, it did not run as expected

I clicked on this link for my angular 2.0 tutorial journey. I managed to successfully display the list of drugs, but encountered an issue when I attempted to create the AuthorComponent. Unfortunately, my app stopped running due to the following error: Er ...

Found in the NgModule.imports section of the AppModule, yet was unable to be identified as an NgModule class in Angular version 12.2.9

Just set up a fresh angular 12 application and installed version 12 of @angular/material. Now I'm trying to implement it by adding this basic element: <mat-drawer-container></mat-drawer-container> However, all I see in the browser is a wh ...

Angular4 provider being integrated into an AngularJS application offers the provider functionality

I have recently migrated my app from AngularJS to Angular4. Now, I want to create a provider in Angular4 and inject it into the app.config in AngularJS. Here is what I currently have: import { UtilsService } from './../utils/utils.service'; imp ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Setting a maximum value for a text box input in Angular for enhanced bot functionality

Currently, I am working with Angular 7 and I find myself trying to incorporate the min and max properties into a textbox. However, I seem to be encountering some difficulties in achieving this. <div> <input type='text' [(ngModel)]= ...

What is the best way to reach the parent controller's scope within a directive's controller?

In a scenario where I have a custom directive nested inside a parent div with a controller that sets a variable value to its scope, like this: html <div ng-controller="mainCtrl"> <p>{{data}}</p> <myDirective oncolour="green" ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...