`How can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in:

HTML:

<div *ngFor="let report of reports">
    <div *ngFor="let i  of income">
        <div *ngIf="report.r_income_id == i.income_id">
            <div *ngFor="let c  of costs">
                <div *ngIf="i.i_costs_id == c.costs_id">
                    {{c.name}}
                </div>
            </div>
        </div>
    </div>  
</div>

However, displaying data based on a specific selected identifier requires implementation in TypeScript. Without testing it yet, I am aware that the second condition may result in undefined due to the value of this.income.i_costs_id. These two conditions should ideally be merged into one. How can this be achieved?

TypeScript:

reports: Reports[]
income: Income[]
costs: Costs[]
selectedReport = null
filteredIncome = []
filteredСosts = []

onSelectedReport(reportId) {
    this.selectedReport = this.reports.find(
      el => {
        return el.report_id === reportId
      }
    )
    if (this.incomeService) {
      this.incomeService.fetchAll().subscribe(
        income => {
          this.income = income
          this.filteredIncome = this.income.filter(
            (income) => income.income_id == this.selectedReport.r_income_id
          )
        }
      )
    }
    if (this.costsService) {
      this.costsService.fetch().subscribe(
        costs => {
          this.costs = costs
          this.filteredСosts = this.costs.filter(
            (costs) => costs.costs_id == this.income.i_costs_id
          )
        }
      )
    }
}

Answer №1

Try

  data: Data[]
  revenue: Revenue[]
  expenses: Expenses[]
  selectedData = null
  filteredRevenue = []
  filteredExpenses = []

  onSelectedData(dataId) {
    this.selectedData = this.data.find(
      el => {
        return el.data_id === dataId
      }
    )
    if (this.revenueService) {
      this.revenueService.fetchAll().subscribe(
        revenue => {
          this.revenue = revenue
          this.filteredRevenue = this.revenue.filter(
            (revenue) => revenue.revenue_id == this.selectedData.r_revenue_id
          )
          if (this.expensesService) {
            this.expensesService.fetch().subscribe(
              expenses => {
                this.expenses = expenses
                for(let r of this.filteredRevenue){
                  for(let e of expenses){
                    if(e.expenses_id==r.r_expenses_id){
                      this.filteredExpenses.push(e)
                    }
                  }
                }
              }
            )
          }
        }
      )
    }
  }

Answer №2

Your situation aligns with the concept of forkJoin. Below is a sample code snippet that you can adjust to suit your specific requirements.

let requests = [];

if (this.incomeService) {
  // Including income service request
  requests.push(this.incomeService.fetchAll());
} else {
  // Adding null as an observable placeholder for the first request
  requests.push(Observable.of(null))
}

if (this.costsService) {
  // Including cost service request
  requests.push(this.costsService.fetch());
} else {
  // Adding null as an observable placeholder for the second request
  requests.push(Observable.of(null))
}

// Sending out the requests concurrently using forkJoin
Observable.forkJoin(...requests)
  .subscribe(values => {
    // Accessing the results
    console.log(values[0], values[1]);
    // Make sure to handle values[0] being null to prevent the unnecessary call to values[1]
    // Here, values[0] corresponds to the result of the first request and values[1] corresponds to the result of the costs service call
  });

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

typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import { getMessaging } from "firebase-admin/messaging ...

Cypress: Importing line in commands.ts is triggering errors

After adding imports to the commands.ts file, running tests results in errors. However, in commands.ts: import 'cypress-localstorage-commands'; /* eslint-disable */ declare namespace Cypress { interface Chainable<Subject = any> { c ...

Object autofill - Typescript utilizing Angular 5

I am working with an object called "features." Here is an example of the object: [{"_id":"5af03d95c4c18d16255b5ac7","name":"Feature 1","description":"<p>Description</p>\n","neworchange":"new","releaseId":"5aead2d6b28715733166e59a","produc ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...

Exploring deep levels of nested FormArrays with Angular 2 and FormBuilder

Currently diving into Angular 2, I am embarking on the challenge of constructing a nested form, validating it, and adding new objects Projects to object GroupProject. Here is a snippet from my TypeScript file: ngOnInit() { this.myForm = this. ...

The value returned by Cypress.env() is always null

Within my cypress.config.ts file, the configuration looks like this: import { defineConfig } from "cypress"; export default defineConfig({ pageLoadTimeout: 360000, defaultCommandTimeout: 60000, env: { EMAIL: "<a href="/cdn-cgi/ ...

Primeng could not locate the material theme

Within my Angular application, I have incorporated the primeng npm package using npm install. Following the instructions provided on the GetStarted page for primeng, it is mentioned that the library includes 32 free themes. However, upon exploring the node ...

Retrieving header information in Angular 6

I am currently working on an example that I found on this website, but I seem to be facing an error that I can't figure out. Even after carefully reviewing my code, I'm still unable to pinpoint the mistake. Specifically, when I use "response => ...

A complete guide to incorporating Angular to hide a Bootstrap 4 Modal using jQuery

After adding jQuery and Bootstrap to the package, I encountered an issue where the modal function was not working properly. Typescript & HTML import $ from 'jquery'; export class AppComponent { name = 'Angular ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Error encountered when attempting to open PDF documents located in the ./../../../assets/pdf/file.pdf directory. Route matching failed, resulting in inability to access the

In my Angular application, I have stored the PDF file under the assets/pdf directory. Here is the code snippet: <div class="container-fluid mt-2 mb-2"> <a target="_blank" href="./../../../assets/pdf/MSW - Transition Briefing Slides v1.1.pdf"& ...

Angular: Refresh Mat-Table data following any changes

I'm currently working with a Mat-table that has expandable rows, each containing an update functionality for the data. While the POST and GET requests are functioning properly, I encounter an issue where I need to reload the page in order to see the u ...

NPM displaying an error message

npm ERROR! Windows_NT 6.3.9600 npm ERROR! Command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\np ...

What is the reason behind the restriction on creating circular dependencies in Ionic applications?

Working with Ionic, I have created 2 services to provide data: export class DocumentService { constructor(favorisService: FavorisService) { } async GetById(id: number): Promise<DocumentModel>{ let path = this.favorisService.getPath(); ...

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...