Removing a particular item from an Observable of arrays containing any type

My application has an Observable that contains an array of places:

places: Observable<Array<any>>;

In the template, I am using the async pipe to iterate over the array:

<tr *ngFor="let place of places | async">
  ...
</tr>

After certain user actions, I need to remove a place with a specific id from this array. However, the code snippet I have tried does not work as expected:

deletePlace(placeId: number): void {
  this.apiService.deletePlace(placeId)
  .subscribe(
    (res: any) => {
      this.places
        .flatMap((places) => places)
        .filter((place) => place.id != placeId);
    }, 
    (err: any) => console.log(err)
  );    
}  

Can anyone provide guidance on how to achieve this functionality?

Answer №1

It's not possible to update an observable directly as it doesn't retain states, but you can respond to events triggered by it.

In your scenario, utilizing the scan operator and merging two streams into one would be a good approach:

  • One stream for initial loading
  • Another stream for delete events

Here is an example implementation:

let obs = this.http.get('/data').map(res => res.json());

this.deleteSubject = new Subject();

this.mergedObs = obs.merge(this.deleteSubject)
.startWith([])
.scan((acc, val) => {
  if (val.op && val.op==='delete') {
    var index = acc.findIndex((elt) => elt.id === val.id);
    acc.splice(index, 1);
    return acc;
  } else {
    return acc.concat(val);
  }
});

To delete an element, simply emit an event on the subject:

this.deleteSubject.next({op:'delete', id: '1'});

Check out this plunkr for a working demo: https://plnkr.co/edit/8bYoyDiwM8pM74BYe8SI?p=preview.

Answer №2

To make the most of the filter operator, follow this method:

this.items$
        .pipe(
            map(items => {
                // Add your specific condition here to filter out items that meet the condition
                return items.filter(item => item.itemId !== 0);
            }),
            map(response => (this.values$ = of(response)))
        )
        .subscribe(result => console.warn('Filtered Result: ', result));

Answer №3

Updated with RxJS version 6

When using the solution provided for RxJS 6 and typescript, an error may occur due to different types being held by the observables. It is recommended to utilize combineLatest, as opposed to zip which will not function properly. Curious why? Find the explanation here :)

combineLatest([
  this.items$,
  this.deleteItem$
]).pipe(
  takeUntil(this.onDestroy),
  tap(([items, deleteItem]) => {
    if (deleteItem && deleteItem.op === 'deleteItem') {
      var index = items.findIndex((item) => item.id === deleteItem.id);
      if (index >= 0) {
        items.splice(index, 1);
      }
      return items;
    }
    else {
      return items.concat(deleteItem);
    }
  })
).subscribe();

Proceed to trigger the event..

this.deleteItem$.next({ op: 'deleteItem', id: '5e88fce485905976daa27b8b' });

I trust this information proves helpful to someone.

Answer №4

The filter functionality remains constant and does not alter the original array.

I propose updating the deletePlace function as follows:-

deletePlace(placeId: number): void {
  this.apiService.deletePlace(placeId)
  .subscribe(
    (res: any) => {
      this.places = this.places.filter((place) => place.id != placeId);
    }, 
    (err: any) => console.log(err)
  );    
}  

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

The output display is not visible

I am currently working on a tutorial to showcase contact details on my webpage. However, I am facing an issue where the code is not displaying the first and last name as expected. Below is the code snippet for reference. Snippet from index.html <!DOCT ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

"Exploring the World of Button Coloration

I'm struggling with customizing the colors of each of the 4 buttons that link to different tables using CSS. I want to assign a specific color to each button, like red for the first one and blue for the second. Your assistance in this matter would be ...

What is the best way to access a value from a service scope in Angular 2?

I am working on an Angular 4 app and have a function to print content. Below is a snippet from my TypeScript file: print(id) { // console.log(temp) this.templateservice.getTemplateById(id).subscribe(template => { if (!template.success) { this.sna ...

Can the Three.js WebGLRenderer be utilized on a node.js server environment?

There seems to be conflicting opinions on whether running WebGLRenderer on the server is feasible. Some say it can't be done, while others claim they are making efforts to achieve it but haven't succeeded yet. Is there a way to accomplish this? ...

Stretching a row in Wordpress Visual Composer and setting the direction to Right-to-Left

Whenever I attempt to expand a row using the row settings in Visual Composer, the row stretches but the alignment of the row becomes completely off. This issue only occurs when the body direction is set to direction:rtl in the CSS. You can view the websit ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

Conceal virtual keyboard on mobile when in autocomplete box focus

I would like the keyboard to remain hidden when the autocomplete box is focused or clicked, and only appear when I start typing. The code below currently hides the keyboard when any alphabets or numbers are pressed. However, I want the keyboard to be hidd ...

Issue with Pop Up not redirecting correctly after a successful login in Azure AD

I recently integrated Azure AD with my web application. When clicking on the login window, a pop-up appears with the URL . It prompts for the Azure AD username and password. However, after successfully logging in, a code is returned as a parameter but the ...

Tips for keeping the Menu bar at the top of the page while scrolling from the middle

I came across a technique mentioned here that I wanted to implement. I used this jsfiddle link (which worked well) to create my own version http://jsfiddle.net/a2q7zk0m/1/, along with a custom menu. However, now it seems like it's not working due to a ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

Activate AngularJS autocomplete when populating the input field using JavaScript

I'm currently facing an issue with updating the value of an input field on a website using JavaScript. Although I can successfully update the input field's value, I find that I am unable to trigger the autocomplete feature. Interestingly, when ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Major Technical Issues Plague School-wide Celebration

In my JavaScript code, I am creating a 16x16 grid of divs. Each div should change its background color from black to white when the mouse enters (inherited based on a common class). However, I am facing an issue where all the divs change color simultaneou ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

The Angular JS Root scope is modified after submitting a form

I'm new to Angular JS and I'm trying to figure out how to save an object into $rootScope in my application. However, when I try to make a post request without including the object from rootScope, it doesn't work as expected. Now, on a newly ...