Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called 'Id' that matches the URL parameter 'id'. My goal is to display only the matching object on the page.

Currently, I am using ActivatedRoute to retrieve the active parameter Id, which is working perfectly. But when I attempt to filter by paramsId.id, it results in an empty array. Strangely, if I replace paramsId.id with a known number used as an Id within the array, the filtering works correctly. Additionally, I can log the value of paramsId.id without any issues, but it fails to work within the filter function.

Successful Filter:

return animal.id === 5;

Failed Filter:

return animal.id === paramsId.id;

Below is the portion inside my component ts file:

constructor(private activatedRoute: ActivatedRoute, private animalService: AnimalService) { }

  ngOnInit() {

    this.animalService.getAnimals().subscribe(animals => {

      this.animals = animals;

      this.activatedRoute.params.subscribe(paramsId => {

        const filteredAnimal = this.animals.filter(function(animal) {
          return animal.id === paramsId.id;
        })

        console.log(filteredAnimal);

      });

    });

  }

Any assistance would be highly appreciated.

Answer №1

Your current approach is facing an issue because paramsId.id contains a string while animal.id is a number. Since "5" is not equal to 5, you need to use parseInt(paramsId.id) in order to compare them accurately.

A more effective solution would involve implementing a method in your service called getAnimal. This method should take an animal id as input and return the corresponding animal object.

animal$ = this.activatedRoute.params.pipe(
  map(params => parseInt(params.id)),
  switchMap(id => this.animalService.getAnimal(id))
);

You can then utilize the animal$ observable in your template using the async pipe.

<ng-container *ngIf="animal$ | async as animal">
  {{animal | json}}
</ng-container>

This way, you don't need any additional subscriptions.

In the service code:

getAnimal(id: number) {
  return this.getAnimals().pipe(
    map(animals => animals.find(animal => animal.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

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

A variety of personalized Vimeo play buttons

Recently, I stumbled upon a genius solution by Chris Coyier for creating custom Vimeo play buttons. It worked perfectly for my needs, but now I'm facing a challenge - how to make it function with multiple videos on the same page. I tried swapping out ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

Challenges faced with password hashing in Express.js

Can anyone assist me with the process of hashing passwords? I had a functional login/register feature on my express app until I integrated bcrypt. After registering a User, I can see that the password is hashed in the Database. However, when attempting to ...

Utilize annotations for both request and response filters to enable client-side routing in Quarkus for forwarding purposes

Currently, I am utilizing Quarkus version 3.4.3 to serve as the backend for my REST endpoints and also host my Angular SPA which acts as a simple interface for interacting with those rest endpoints. The issue I am facing is quite common - I need client-si ...

What is the best approach to incorporate Column Reordering in react-data-grid?

Within my REACT application, I have incorporated the npm package react-data-grid. They offer a sample showcasing Column Reordering on their website. I wish to replicate this functionality in my own code. Upon reviewing their source code, I am puzzled abou ...

Issues with the Rendering of Child Components in React

I have developed a main component that contains two child elements, where one of the children is attempting to send data back to the parent's state. I am not encountering any runtime errors when running the code, but the child component that is suppos ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

Generating forms dynamically using JSON data

Currently, I'm using three nested ng-repeat directives to display multiple questions and their corresponding answers. Everything is displaying correctly so far, but now I need to create a form to save the answers. What would be the best approach to ac ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

Discovering the root cause of performance issues in a v14 Angular application

I am currently working on a web application built with Angular 14. During my testing with Lighthouse, I have discovered that the performance of the application is satisfactory on desktop but falls short for mobile users. The application consists of three ...

What is the best method for importing several components from a directory in ReactJS?

I'm looking for a way to import multiple React components from a directory without having to export them separately in an index.js file. Here's the structure of my directory: src/ components/ comp1.js comp2.js comp3.js ...

How can I incorporate popups in React using mapbox-gl?

Currently utilizing mapbox-gl within React, everything seems to be functioning properly except for the integration of mapbox-gl's Popups. I have the function let Popup, but I am uncertain about how to incorporate it. renderMap() { if (this.props. ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Make sure to execute the fire directive only when ng-repeat has completed

Currently, I am utilizing owl carousel with data being fetched through an Ajax call. Once the data populates the HTML content using ng-repeat, I need to trigger the directive that initializes the owl carousel. How can I achieve this? One approach I consid ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...

Setting up Angular2 webpack to run behind a reverse proxy on a subpath

I am looking to configure angular2-webpack-starter behind an Apache reverse proxy with URLs starting with a fixed prefix like /angular2-webpack-starter/. I came across this setting: output: { publicPath:"angular2-webpack-starter", ... Is this the cor ...

jQuery opacity transition not functioning properly while all other animations are working fine

I've encountered quite a peculiar issue: Using jQuery v11 on the latest version of Chrome localhost, I can successfully apply jQuery.animate() to various elements and features on my website, including opacity. However, there is one particular element ...

Unanticipated commitments fulfilled on the spot

While troubleshooting a setup for managing promise concurrency in handling CPU-intensive asynchronous tasks, I encountered perplexing behavior that has left me puzzled. To regulate the flow, my approach was to initially create an array of Promises and the ...