extracting a targeted subset of information from the retrieved dataset

My objective is to filter specific data from a database and display it on the page. I planned to utilize the httpClient get method in the service to retrieve only the desired data. However, I am unsure about how to effectively handle the filtering process.

Currently, I am able to fetch all the available data through a testurl but I need assistance with filtering out the specific entries.

data.json

[
    {"allOrders":21},
    {"pendingConfirmOrders":14},
    {"pendingPaymentOrders":8}
]

order-history.component.ts

import { orderHistoryService } from './../../infrastructure/services/order-history.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-order-history-page',
  templateUrl: './order-history-page.component.html',
  styleUrls: ['./order-history-page.component.scss']
})
export class OrderHistoryPageComponent implements OnInit {
orderHistory:any;
confirmOrder;
  constructor(private orderService:orderHistoryService) {
    this.orderService.getOrderHistory().subscribe((response:any)=>{
      this.orderHistory = response;
    });
   }
  _orderHistory(){
    console.log(this.orderHistory);
  }
  _pendingConformation(){
    this.confirmOrder=this.orderHistory.filter(orders=> this.orderHistory
      .includes(this.confirmOrder));
  }

  ngOnInit() {
  }

}



orderService.ts

import { Injectable } from '@angular/core';
import { AppSettings } from '../../app.setting';
import { ApiService } from './api.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class orderHistoryService {
    private testUrl='../../../assets/data/orders.json';
//   _baseUrl = AppSettings.BACKEND2_SUBSCRIBE_BASE;
  constructor(private _apiService: ApiService, private _http: HttpClient) { }
  getOrderHistory():Observable<any>{
    return this._http.get<any>(this.testUrl);
    //  const endpoint = `${AppSettings.SERVER_API}`//endpoint;
    //  return this._http.get(endpoint);
  }
  /**
 * THIS METHOD GET The history of orders
 */
}

The functions I have implemented currently result in an empty array being returned.

Answer №1

When dealing with data.json, which consists of an array of JSON objects, it is important to include the array index when creating JavaScript variables to store the information from your API response.

Here is an example of how you can create these variables:

allOrders = orderHistory[0].allOrders;
pendingConfirmOrders = orderHistory[1].pendingConfirmOrders;
pendingPaymentOrders = orderHistory[2].pendingPaymentOrders;

This approach will only be effective if you are certain that the structure of data.json will remain consistent. If possible, I recommend modifying the API output to eliminate the need for arrays and instead have a structure like this:

{
"allOrders":21,
"pendingConfirmOrders":14,
"pendingPaymentOrders":8
}

By doing this, you would no longer need to include array indexes and can access the data directly as demonstrated in your previous comment - using

orderHistory.pendingConfirmOrders;

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

Issues arise when certain features in the Typescript 3+ version do not seem to be functioning properly, despite being installed

I have globally installed Typescript version 3.7.3 and Visual Studio Code is using the same version, yet I am unable to access functionality specific to Typescript 3+. For example, when trying to declare a variable with the type "unknown", I encounter a co ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

Struggling to transfer information between different components?

I recently implemented a delete button functionality in my project to remove elements when clicked, but I'm facing an issue where the input decorator is not properly receiving data for deletion. When I console log, it shows that the array is empty whi ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

When parent components reference child components, their values appear as null

I'm dealing with both a parent component and a child component in my project. The child component contains a form that should be saved if the user makes changes and then tries to navigate away by clicking on a link within the parent component. Parent ...

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

Encountering a 403 Error when Configuring POST Requests in Angular 6 Proxy

Currently troubleshooting a local Angular 6 application with the command ng serve --proxy-config proxy.conf.json. Here's a snippet of my proxy.conf.json file: (target has been changed for security purposes) { "/**": { "target": "http://my-main- ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

Is there a way to refresh an Angular page without reloading it?

Using Angular 7, I have a main page with numerous buttons, each featuring a progress bar like this: https://i.sstatic.net/Pxrby.png When interacting with a component and then closing it, the progress bar on the button should update. The MatDialog functio ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

unable to access data through ngmodel

Encountering an issue where I cannot read the value and bind it to a variable using ng model. It is showing as undefined in the console. yy.ts let searchTerm = ''; console.log(searchTerm) yy.html <input class="ml-3" [(ngModel)]= ...

Show an HTML image with the file chosen through the FileDialog prompt

After spending about four hours searching for a method to display the image file chosen by FileDialog in a browser within an img tag, I came across various pages suggesting updating the src attribute of the img tag with the content of the file. However, th ...

The specified property is not found within this type (Union type)

When working with one of multiple interfaces, I encounter an issue in Vue where it claims the property does not exist. export interface Link { to: string text?: string; } export interface Text { text: string; } export interface Html { html: string ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

What purpose does @ViewChild serve if we are unable to modify or interact with its properties from the Parent Component?

I have two main components - home and about. Within both of these, I am including a third component called hearts. Currently, I am manipulating the value of the 'age' property in the hearts component (initially set to '23') using @ViewC ...

Accessing values through indexes in a TypeScript Set collection

Greetings to all! I am a TypeScript newcomer and it seems like there is something that I'm missing. Here's my query: const someSet = new Set(); someSet.add(1) console.log(someSet[0]) When I run this, it returns undefined. Can someone please cla ...