How to connect multiple HTTP requests using observables in Angular 7

Is there a more efficient way to remove an alert only if it is not assigned to any user? Currently, I am checking my users list and filtering out the users who have this alert assigned using observables. But I wonder if there is a better approach to achieve this task.

deleteAlert(id: number) {
  this.usersService.getUsers().subscribe(
    (users) => {
      if (users.filter((value) => value.alert.id === id).length > 0) {
        console.log('Deassign alert from all users first');
      } else {
       this.alertService.deleteVillain(id)
        .subscribe(() => {
          this.alertsList =this.alertsList.filter(alerts=>alerts.id!==id);
        });
    }
  }
 )}

Answer №1

To implement the functionality, you can utilize the flatMap operator as specified in this helpful resource.

manageAlert(id: number) {
      this.usersService.getUsers().flatMap(
        (users) => {
          if (users.filter((value) => value.alert.id === id).length > 0) {
            console.log('Reassigning alert to all users first');
          } else {
           return this.alertService.deleteVillain(id);
        }
      }).subscribe(data=>{
         this.alertsList = this.villainsList.filter(alerts=>alerts.id!==id);
      });
}

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

Detection of collisions using bounding sphere method

In Three.js, each mesh (THREE.Object3D) comes with useful properties like boundingSphere and boundingBox, along with methods such as intersectsSphere and isIntersectionBox. I initially thought I could use these for simple collision detection. However, I n ...

Is it feasible to restrict generic classes for particular functions?

Imagine creating a customized container in TypeScript. Let's consider this straightforward example: class Container<T> { val: T; constructor(t: T) { this.val = t; } } Now, let's say you want to implement a function that can gene ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Minimum requirement for browsers such as IE9 and other compatible versions

My web app requires IE9 - what are the equivalent browser versions for Firefox, Chrome, Opera, and others? I am able to detect the user's current browser and version, and if it is not compatible, I am considering providing links for them to download ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

Is there a way to construct a Javascript function, without relying on JQuery, for fetching JSON objects from varying

I have been searching for a non-JQuery AJAX function that can fetch data from a URL and return it as a JSON object. For example, let's say I want to display information about Users from one JSON located at URL1 and also include information about Post ...

Retrieve an array from a JSON object by accessing the corresponding key/value pair using the utility library underscore

I have a dataset in JSON format (as shown below) and I am attempting to use the _.where method to extract specific values from within the dataset. JSON File "data": [{ "singles_ranking": [116], "matches_lost": ["90"], "singles_high_rank": [79 ...

Nodejs: The JSON.stringify method is automatically rounding the numbers

I am encountering a strange issue. When I call the credit card processor (CCBILL) with a payment token, they return a subscription ID. For example, 0124058201000005323 should be returned but what I receive is 124058201000005330, indicating that it has been ...

Error encountered when processing a PUT request for a node causing a

After receiving minimal views and replies on a similar question I posted last night, I am reaching out again in hopes of resolving my issue. For the past two days, I have been struggling to fix this problem and progress with my project! If you are interes ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

The LOAD event in Highchart seems to be malfunctioning

function drawGraph($scope) { // Customized graph drawing function $scope.chartConfig = { chart: { type: 'spline', animation: Highcharts.svg, marginRight: 10, events: { ...

Incorporating a fixed header title when creating a customizable table

I am working on creating a dynamic table with rows and columns based on JSON data. JSON: $scope.dataToShow=[ tableHeder=["First Name","Age"], { name:"rahim", age:23 }, ...

Choosing the following choice using the Material-UI Select tool

Looking for a way to enhance my dropdown select from MUI in a Nextjs application by adding two arrows for navigating to the next/previous option. Here's what my code currently looks like: <StyledFormControl> <Select value={cu ...

Error message indicating the Ionic 5 Phonegap-NFC plugin is not installed, even though it has been successfully installed

While utilizing the NFC library, I followed the Ionic documentation recommendations at (https://github.com/chariotsolutions/phonegap-nfc) and (https://ionicframework.com/docs/native/nfc). However, when trying to access the code in my component that calls ...

"Fill out the form fields by selecting a row option from the dropdown menu in response

Here is my working example of retrieving addresses associated with the current user who is logged in. The mysqli query is successfully printing the options for addresses stored in the mysql database, which are linked to the session username. Addresses are ...

The directive isn't functioning within a submodule

I am facing an issue with getting a directive to function properly in a lazy loaded module. Even after carefully reviewing the documentation and adding the directive to the declarations array of my main module, the directive works fine in the main module b ...

What are the best practices for passing the type of getServerSideProps to the page props in Next.js?

After discovering two working solutions, I am unsure which approach is more consistent. interface ICatalogHome { response: Result<CatalogHomePageResponse>; } export const getServerSideProps: GetServerSideProps<ICatalogHome> = async (contex ...

Is it considered acceptable to utilize a v-model's value as the basis for an if-statement?

How can I incorporate the v-model="item.checked" as a condition within the validations() function below? <table> <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" > <div> <td> ...