I've been stuck for hours, is there anything I should include?

I'm attempting to access http://localhost:4200/Personnes/view/:2, but I encountered the following error (ERROR TypeError: Cannot read property 'nom' of undefined)

"My personnnes.service.component.ts"

`export class PersonnesService {
baseUrl='http://localhost/api' ;
personnes: Personne[] = [] ;

constructor(private http:HttpClient) { }

getAll():Observable<Personne[]>{
return this.http.get(`${this.baseUrl}/list`).pipe(
map((res)=>{
this.personnes=res['data'] ;
return this.personnes ;
}),
catchError(this.handleError)) ;
} ;

private handleError(error :HttpErrorResponse){
console.log(error) ;
return throwError('Erreur sur qlq chose.') ; 
}

store(personne: Personne): Observable<Personne[]> {
return this.http.post(`${this.baseUrl}/store`, { data: personne }) 
.pipe(map((res) => {
this.personnes.push(res['data']);
return this.personnes;
}),
catchError(this.handleError));
}

getSinglePersonne(id:number)
{
const pers=this.personnes.find(personneObject =>  personneObject.id === 
id) ;
return pers ;
}`

"My single-personnne.component.ts"
`export class SinglePersonneComponent implements OnInit {

personne =new Personne(0,'','','') ;

constructor(private route:ActivatedRoute,
private personnesService:PersonnesService,
private router:Router) { }

ngOnInit() {   
const id=this.route.snapshot.params['id'] ;
this.personne = this.personnesService.getSinglePersonne(+id) ;
}`

"My template single-personnne.component.html" `

<div>
<h2>Nom :</h2>
<h3>{{personne.nom}}</h3>
</div>
<div>
<h2>Prénom :</h2>
<h3>{{personne.prenom}}</h3>
</div>
<div>
    <h2>Numéro Téléphone:</h2>
    <h3>{{personne.numTel}}</h3>
</div>

 <button class="btn btn-default" (click)="updatePers()">Modifier</button>

` I anticipate retrieving a person with the ID=2 and wish to showcase it in the template

Answer №1

When accessing the page at

http://localhost:4200/Personnes/view/:2
, note that the id is set to ':2', causing a problem when trying to retrieve data using
this.personnesService.getSinglePersonne(+id)
. The addition of '+id' results in the value being 'NaN', which means you are attempting to find a person with an id of 'NaN', leading to a comparison of id === NaN, always resulting in false. To resolve this issue, simply modify your url to
http://localhost:4200/Personnes/view/2
and the functionality should be restored.

Answer №2

Here is an example of how your service method and component should be structured:

    return this.http.get(`${this.baseUrl}/list`).pipe(
        map(res => {
            return res['data'];
        }),
        filter(person => person.id === id),
        catchError(this.handleError)
    );
}

And in the component:

ngOnInit() {   
    const id=this.route.snapshot.params['id'] ;
    this.personnesService.getSinglePersonne(id).subscribe(person => this.personne = person);
}

Answer №3

Your function named getSinglePersonne is returning an empty pers for a specific id. This could be due to two reasons:

  1. The particular id does not exist in the array
  2. Or the condition personneObject.id === id is causing issues. While it is recommended to use ===, you can try using == to check if this is the problem.

Since the service method is not returning any matching object, this.personne remains undefined, leading to the error you are encountering.

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

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

Incorporating Kendo UI and NGX Bootstrap within an Angular application

Currently, I am in the process of developing an Angular application and incorporating the NGX-Bootstrap library. While researching, I came across the Kendo UI library which offers a variety of interesting components. Is it feasible to utilize both librarie ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

Stop users from logging in simultaneously on multiple systems

It is possible for the same user and password to be used on multiple computers simultaneously! If person 1 is logged in with a certain username and person 2 logs in from another computer or browser using the same credentials, person 1 will not be automatic ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

Encountered an issue launching the advanced web server and reverse proxy server nginx for high performance

UPDATE - Recently, I encountered the following error logs: nginx: [emerg] unknown "request_url" variable Aug 19 01:14:58 nginx[4890]: nginx: configuration file /etc/nginx/nginx.conf test failed Below is my nginx.conf file: user www-data; worker ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Steps to deactivate an angular material component on version 2.0.0-beta.5

Recent updates have led to an error in my code: Error at /Users/asaylor/Desktop/RevenueIQ/website/aot/node_modules/@angular/material/typings/index.ngfactory.ts:4236:30: Property 'disabled' does not exist on type 'MdCheckbox' I am enc ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Trapped in a never-ending cycle caused by failing to dispatch an action within ngrx/effects

My current setup involves using Angular2, ngrx/store, and ngrx/effects for state management. I have encountered an issue where I am unable to display an error message when a specific action fails within an @Effects() block. Here is the problematic code sn ...

Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach: service.ts getRDV() { this.rdvList = this.firebase.list('/rdv'); return this.rdvList; } Model: export class RDV { key: ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Obtaining information from an API using Angular

I am currently working on extracting data from various API's and I am encountering some difficulties. The initial part is functioning correctly, with the code provided below : ngOnInit(): void { this.http.get('http://.../api/getData?table=ge ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

Guide on deactivating the div in angular using ngClass based on a boolean value

displayData = [ { status: 'CLOSED', ack: false }, { status: 'ESCALATED', ack: false }, { status: 'ACK', ack: false }, { status: 'ACK', ack: true }, { status: 'NEW', ack ...

Issue: The provider specified for the NgModule 'AppModule' is invalid - it should only be instances of Provider and Type, but instead received: [?[object Object]?, ...]. This error occurred within Ionic framework

While working on my IONIC project, I encountered an error when adding Geolocation to my providers. Removing it from the providers allows my app to function properly, but even my professor couldn't solve the issue. Here is the content of my file: impor ...

Oops! The OPENAI_API_KEY environment variable seems to be missing or empty. I'm scratching my head trying to figure out why it's not being recognized

Currently working on a project in next.js through replit and attempting to integrate OpenAI, but struggling with getting it to recognize my API key. The key is correctly added as a secret (similar to .env.local for those unfamiliar with replit), yet I keep ...

React TypeScript - Issue with passing props to Hooks causing type errors

I have set up a codesandbox project to demonstrate my problem 1) Initially, I created the <Input> component for styling and tracking input content. 2) While everything was functional, adding more forms prompted me to create a useInput hook for easi ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

Both buttons are calling the same function in Angular 6

I have created a component called add-customer.component.html <form [formGroup]="addCusForm"> <div id="login-container"> <h2 class="add-title">Customer Details</h2> <mat-form-field class="example-full-width ...