`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

Attempting to incorporate an npm package (specifically Howler) into an Angular 2 application

I'm facing an issue with importing Howler into my Angular 2 app as it doesn't have a typings file. Despite my efforts in searching for a solution, I haven't been able to find anything helpful. Can someone guide me on how to import "howler" i ...

Disable dates that are more than 7 days from the current date using Material UI's Date

How can I restrict users from selecting dates more than 7 days after their initial selection? In the example image provided, the date of January 30th should be disabled for selection. https://i.stack.imgur.com/iTem4.png Below is the code snippet: const ...

Extract values from an object using Typescript

Here is my JavaScript code: const { a, b, c } = { a : "hello", b : "stackoverflow", c : "it's greate" }; I am interested in converting this to TypeScript. Is there any solution for this? ...

How to upgrade Angular Header/Http/RequestOptions from deprecated in Angular 6.0 to Angular 8.0?

When working on http requests in Angular 6.0, I typically follow this block of code. I attempted to incorporate the newer features introduced in Angular 8.0 such as HttpClient, HttpResponse, and HttpHeaders. However, I found that the syntax did not align ...

Create a union type by utilizing indices of an array type

For instance: type BasicTheme = { name: 'basic'; colors: [string, string]; }; type AdvancedTheme = { name: 'advanced'; colors: [string, string, string, string]; }; type MainColor = ???; // 'main-1' | 'main-2&apo ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

How to effectively implement React Context with the useState hook in a TypeScript project

I've been working with code that resembles something like the following: SomeContext.ts: export interface SomeContext { someValue: string; someFunction: () => void; } export const defaultValue: SomeContext = { someValue: "", som ...

Encountering a TypeScript issue when integrating @material-tailwind/react with Next.js 14

Attempting to incorporate "@material-tailwind/react": "^2.1.9" with "next": "14.1.4" "use client"; import { Button } from "@material-tailwind/react"; export default function Home() { return <Button>Test MUI</Button>; } However, the button i ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Is there a solution for resolving the Element Implicitness and Lack of Index Signature Error?

I encountered an issue with specialCodes[letter]. It mentions that The element implicitly has an 'any' type because the expression of type 'string' cannot be used to index type and No index signature with a parameter of type 'strin ...

Issue with Angular 5: Data not being correctly bound following a redirect

Encountering an issue with data binding when redirecting from one view to another. I am inputting form data in the "http://localhost:4200/create" view and then navigating to "http://localhost:4200/settle/9ed5509c-ecd6-4895-96eb-a2efa04bae6d" (URL with toke ...

Align the headers of columns to the right in the AgGrid widget

Is there a way to align the column headers to the right in AgGrid without having to implement a custom header component? It seems like a lot of work for something that should be simple. You can see an example here: https://stackblitz.com/edit/angular-ag-g ...

Authentication with Angular 4 and Firebase 2

I'm having some difficulty learning how to authenticate users using Angular and Firebase. When I run the Angular app using ng serve in the terminal, I keep getting this ERROR message: ERROR in /Users/.../Desktop/angular/fireauth/node_modules/angul ...

Is it possible to load the surrounding markup in Angular before the guards are resolved upon the initial load of the router-outlet?

Within our Angular 12 application, we have implemented guards that conduct checks through API calls to the backend in order to validate the user's permissions for accessing the requested route. The default behavior of these guards follows an all-or-no ...

I'm really puzzled as to why they would choose to export in this manner in React

I noticed that several files were exported in a similar manner, and I'm unsure why this specific method was chosen. Could there be any advantages or particular reasons for exporting them like this? index.ts export { default } from './Something& ...

Tips for modifying a text input in a list

Managing comment boxes and buttons for each box can be a bit tricky. Clicking on the edit button should enable only that specific textbox, while save or cancel actions should hide the text box and show "<p></p>". Below is my ng-template where ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

Directly retrieve the result from http service (observable) without the need to return Observable from the function

Is there a way to directly return a result from the service without returning Observable and then using then clause? I've experimented with methods like pipe, of, take, toPromise, map, async-await, but none of them seem to return the result on a servi ...

Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to dis ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...