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

Error! Unexpected closure occurred while creating an Angular CLI project with npm

After cloning an Angular (4+) CLI project onto a new machine and running npm install, I encountered an error that reads as follows. This project works perfectly fine on other computers: npm ERR! premature close npm ERR! A complete log of this run can be ...

How can you implement a null filter in the mergeMap function below?

I created a subscription service to fetch a value, which was then used to call another API. However, the initial subscription API has now changed and the value can potentially be null. How should I handle this situation? My code is generating a compile e ...

Can halting an ajax function mid-process prevent it from finishing?

My objective is to convert a video using ffmpeg, which tends to take a considerable amount of time to complete. I'm considering sending an ajax request to the server for this task, but I don't want the user to have to wait until the video convers ...

Utilize Angular Material to assign the value of a mat-select component based on the FormControlName property

I am using Angular version 7 and have encountered an issue with a form I am creating. The form includes a dropdown select to choose an option, but when the page loads, the pre-defined value is not showing up. This page is specifically designed for editing ...

Error Encountered: Visual Studio cannot locate the file 'COMPUTE_PATHS_ONLY.ts' during the build process

Upon fixing my visual studio 2015, an error was thrown that I haven't encountered before. Error Build: File 'COMPUTE_PATHS_ONLY.ts' not found. I did not add COMPUTE_PATHS_ONLY.ts to my Git repository. The other files in the repo rema ...

Unable to confirm the version of Angular

I am currently using node version 10.14.1 and npm version 6.4.1 with angular version 7.0.3 installed. However, when I try to check the angular version by running the ng --version command, I encounter an error message in the command prompt. C:\Users&b ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...

Issue with Angular failing to identify jQuery after transferring the dependency from package.json to bower.json

Initially, my project included angular, angular-bootstrap, and jquery in the package.json file, with everything being compiled using browserify. // package "dependencies": { "angular": "~1.4.6", "angular-bootstrap": "~0.12.2", "jquery": "~2.1. ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Error message stating 'compression is not defined' encountered while attempting to deploy a Node.js application on Heroku

Why is Heroku indicating that compression is undefined? Strangely, when I manually set process.env.NODE_ENV = 'production' and run the app with node server, everything works perfectly... Error log can be found here: https://gist.github.com/anony ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Arrangement of jQuery On Events and Triggers

Consider the code snippet below: $('body').on('hellothere', function(){ console.log('execution complete.'); }); $('body').triggerHandler('hellothere'); The abov ...

Retrieving the chosen option in Vue.js when the @change event occurs

I have a dropdown menu and I want to perform different actions depending on the selected option. I am using a separate vue.html and TypeScript file. Here is my code snippet: <select name="LeaveType" @change="onChange()" class="f ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

The content of btn-id element in Angular is showing as undefined

I have a JavaScript file located at sample/scripts/sample.js and there are 8 HTML files in the directory sample/src/templates/. My goal is to select a button on one of the HTML files. When I tried using angular.elemnt(btn-id).html(), I received an 'un ...

What is the significance of using $timeout in order to activate a watch function?

There is an interesting phenomenon happening with my directive. It watches the height of an element that is being updated by a controller using a factory method to retrieve data. Strangely, unless I include a $timeout in that factory function, my watch doe ...

Retrieving the source code of a specific http URL using JavaScript

Is it feasible to obtain the source code of a webpage using JavaScript on the client side? Perhaps with AJAX? However, can I ensure that the server from which I am downloading the URL sees the client's IP address? Using AJAX could potentially reveal ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...