Retrieve particular items from the API response

What is the best way to access a specific object based on a property from an API response? In my scenario, I have an array of Products retrieved properly from my server. The watchedProducts class has a property called productId which corresponds to the id in the Product object. My question is, how can I efficiently iterate over these arrays to retrieve the products where

watchedProduct.productId == product.id
?

Code:

export class MyProductsComponent implements OnInit {
  watchedProducts: WatchedProduct[] = [];
  products: Product[] = [];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.getWatchedProducts();
  }

  getWatchedProducts(): void {
    this.dataService.getObjects(WatchedProduct).subscribe(result => {
      this.watchedProducts = result.object;
      //get watched product, its work fine
    });

    this.dataService.getObjects(Product).subscribe(result => {
      this.products = ...
      //what to do next? 
      //i want to get that products, where watchedProducts[i].productId == products[i].id          
    });
  }
}

EDIT

I have a SQL Server where the table Products is related to WatchedProducts like parent-child. ProductId in WatchedProducts is FK for Id in Products

products looks like this:

https://i.sstatic.net/W5QSm.png

And watchedProducts:

https://i.sstatic.net/mGME1.png

In this scenario,

Product.id == 8 === WatchedProduct.ProductId == 8

My question is, how to get products array where

watchedProduct.productId == product.Id
?

EDIT2

Based on one answer, I did the following:

getWatchedProducts(): void {
this.dataService.getObjects(WatchedProduct).subscribe(result => {
  this.errorService.showError(result);
  this.watched = result.object;
});
this.dataService.getObjects(Product).subscribe(result => {
  this.errorService.showError(result);
  this.products = result.object;
  for (let i = 0; i < this.watched.length; i++) {
    for (let j = 0; j < this.products.length; j++) {
      if (this.watched[i].productId == this.products[j].id)
        this.watchedProducts.push(this.products[j]);
    }
  }
});

}

Sometimes I need to refresh the browser multiple times to get a response with product objects. Could you help me identify what I am doing wrong here?

Answer №1

Hey @michasaucer, it's important to note that when you subscribe to two different observables, you won't be able to determine which one completes first. One way to handle this is by combining the calls into a single operation using "join".

For example, you can utilize forkJoin:

getWatchedProducts(): void {
    forkJoin(this.dataService.getObjects(WatchedProduct),
             this.dataService.getObjects(Product))
       .subscribe(result=>{
//       result[0] contains response from getObject(WatchedProduct)
//       result[1] contains response from getObjects(Product)

         this.errorService.showError(result[0]);
         this.watched = result[0].object;

         this.errorService.showError(result[1]);
         this.products = result[1].object;
         for (let i = 0; i < this.watched.length; i++) {
           for (let j = 0; j < this.products.length; j++) {
             if (this.watched[i].productId == this.products[j].id)
               this.watchedProducts.push(this.products[j]);
           }
         }
      })
}

Note that there is only one subscribe used here NOTE: I have not made any revisions to your code, just introduced the use of forkJoin

Answer №2

In order to retrieve a single Product from an array, specifically the one that shares the same id value as the Watchedproduct, you will need to implement a Conditional rule like using an if statement.

this.dataService.getObjects(Product).subscribe(result => {
      //what should be done next?
      //I would like to extract those products where watchedProducts[i].productId == products[i].id

      for (let i=0; i<this.watchedProducts.length; i++) {
          if (result[i].productId==this.watchedProducts.id) {
             //perform the required action to store it.
          }
      }

});

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

Error: Trying to access the property 'directoryExists' of an undefined object is not allowed

Embarking on the journey to update my Angular 2 CLI project from 1.0.0-beta.11-webpack.2 to 1.0.0-beta.11-webpack.8 using ng init, and then executing ng serve leads to encountering the subsequent error: ** NG Live Development Server is running on http:/ ...

What is the best way to apply styling to a kendo-grid-column?

Utilizing the kendo-grid in my project serves multiple purposes. Within one of the cells, I aim to incorporate an input TextBox like so: <kendo-grid-column field="value" title="{{l('Value')}}" width="200"></kendo-grid-column> It is ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...

What is the reason for the failure of the error catch function when a 401 error occurs during the refresh token request?

If encountering a 401 error with any other request, the refresh token needs to be executed and there are three possible scenarios: When sending a valid refresh token, it works as expected. Using an invalid refresh token results in a 401 error from the bac ...

Resolving route data in Angular 2 and above

When retrieving data from an API in an Angular route resolver, I encountered a problem where if there was an error due to a stale token, I needed to refresh the token and then retry the API call. Below is the code snippet illustrating this scenario: impor ...

Select characteristics with designated attribute types

Is there a way to create a type that selects only properties from an object whose values match a specific type? For example: type PickOfValue<T, V extends T[keyof T]> = { [P in keyof (key-picking magic?)]: T[P]; }; I am looking for a solution w ...

What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this: MyModule = angular.module('MyModule', ['dependency1', 'dependency2']); MyModule.factory('MyService', ['$other ...

What is the best way to ensure an observable has been updated before proceeding with additional code execution?

Is an observable the best choice for providing live updates of a variable's value to another class? I have a loop in my service class that looks like this: elements.forEach(element => { doStuff(); this.numberSubject.next(valueFromDoStuff); }) ...

Error: The render view is unable to read the 'vote' property of a null object

Within this component, I am receiving a Promise object in the properties. I attempt to store it in state, but upon rendering the view, I encounter the error message "TypeError: Cannot read property 'vote' of null." Seeking a solution to my predic ...

Issue: XHR failure (404 Not Found) while attempting to load angular2/http

I'm currently utilizing angular-cli for my Angular2 application. Whenever I attempt to load angular2/http in my Components/Services, no errors are displayed in the cli terminal. However, the browser's console shows the following message - GET ...

Resize the p-accordion within a p-splitter using PrimeNG programmatically

Please find the code for my component below: In this component, I have a p-splitter that is divided into 3 sections. Each section contains a p-accordion, which in turn includes a p-table. <div class="card w-full"> <p-splitter [p ...

What is the best way to bring attention to a field that is outside the current viewport?

Is there a way to automatically scroll to the specific invalid field after clicking on submit in a large form, without having to manually search for it by scrolling through the page? ...

Is there a way to implement a multiple selection feature in my form without using Angular Material?

I need a method to implement a multiple select feature in my form without relying on angular material. I attempted a simple solution, but it did not function as expected: Here is the HTML code I used: <label>Periods</label> <select for ...

Ways to duplicate a column value in a reusable table

Hi there! Currently, I am implementing a smart table (i.e reusable table) in our application. I need to send data through settings from one component file and retrieve it in the reusable component. However, I am facing an issue with binding nested values i ...

Why am I encountering an HTTP 400 Error when trying to consume the API with a GET request? What could be

I am currently working with a Symfony server that has JWT authentication and an Angular client app that is sending requests. I have successfully implemented a login feature and now I need to retrieve some data to populate a select dropdown. The data I nee ...

Angular 6 compatibility issue with Bootstrap tooltips rendering title attribute

When setting up a bootstrap tooltip in an Angular template, I encountered the following issue: <img src="/img" *ngIf="tooltip.isTrue" [title]="{{toolTip.content}}" class="mb-3 ml-1" [attr.data-trigger]="'hover'" [attr.data ...

Issue with Angular modal not opening as expected when triggered programmatically

I am working with the ng-bootstrap modal component import { NgbModal, ModalCloseReasons } from "@ng-bootstrap/ng-bootstrap"; When I click on a button, the modal opens as expected <button class="btn labelbtn accountbtn customnavbtn" ...

What are the different ways to eliminate the scrollbar in angular, css, js, or html?

I'm a beginner in front-end development and despite searching for a solution, I haven't been able to find an answer. Is there a method to eliminate the scrollbar from my page containing an image? Or are there alternative approaches to maintain a ...

What is the reason behind Typescript's `for...of` creating a copy of the iterable object before iterating through it

For instance: let myList = []; for (let item of myList) { ... } After being transpiled: var myList = []; for (var _i = 0, myList_1 = myList; _i < myList_1.length; _i++) { var item = myList_1[_i]; } Why is myList_1 necessary in this case? You ca ...

Unable to verify the authenticity of every file I choose to upload

Currently, I am in the process of learning how to develop a mean stack app, specifically focusing on creating an ecommerce type application. The main issue that I have encountered revolves around image uploading. My goal is to upload multiple files simult ...