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

Encountered an error while attempting to install the 'ionic-native' package

Currently, I am navigating through this particular link to integrate local notifications into my Ionic 2 application. To kickstart the process, I executed the following two commands: Username@DESKTOP-BNKQVBC MINGW64 ~/Reminder-App (platform-specific) $ n ...

Is the relevance of Angular 1.x still prevalent in today's development landscape

Considering I have several projects in angular 1.x, I'm contemplating whether it's truly essential and efficient to upgrade them to angular 4 or a later version. The smaller dashboards do not necessarily require an update since they are only use ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

Using href with IconButtonProps is not supported

I'm facing a challenge in creating a wrapper for the IconButton. I aim to pass components or href props, but unfortunately, I am unable to achieve this by passing the IconButtonProps. Is there a way to accomplish this? function CustomIconButton(props ...

Issues arise during the migration process of upgrading the project from Angular 8 to Angular 15

I am currently in the process of upgrading an Angular project from version 8.3.26 to a version beyond 12. I know that this should be done incrementally, so my first step is to upgrade to Angular 9. However, when I follow the instructions in the documentati ...

`When the component is loaded, subscribing to the event will work properly.`

I am facing challenges with handling data retrieved from a Database. I want to send it to a central service so that I can utilize it later when loading the components that require this data. The issue I'm encountering is that the central service appea ...

A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error: https://i.stack.imgur.com/zY1io.png Below is the code snippet for the AppModule: @Module({ imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:2 ...

Clicking on the Angular Material Table will reveal the items for display

Only when I click on the table do items display. Upon initially loading the page, the table is empty for reasons unknown to me. I retrieve data from Rest-API Cloud Blobstorage and populate the empty Array with it. Check out the code snippet below: impor ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Unlocking the Power of Authorization Code Grant with PKCE in Angular6+ Applications

Seeking guidance on how to implement the MSAL library in Angular 6+ applications for integration with AZURE AD. After reviewing Microsoft's documentation, I discovered two flows: the 'implicit grant flow' and the 'auth code flow'. ...

How does Vue compare to Angular in terms of components?

Is there a simple way to render dynamic components in Angular similar to how it's done in Vue? In Vue, rendering a dynamic component is as easy as this: <component v-bind:is="'componentX'"></component> How can this be ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

How to use SASS mixins in Angular 5 components

Within my Angular 5 project, I have organized my SASS styles into a separate directory which contains all the variables, functions, and mixins. These are then imported into my main style.scss file. @import 'abstracts/variables', 'abstracts/ ...

Retrieve an enumeration from a value within an enumeration

In my coding project, I have an enum called Animals and I've been working on a function that should return the value as an enum if it is valid. enum Animals { WOLF = 'wolf', BADGER = 'badger', CAT = 'cat', } cons ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

Creating alignment within a form/

These two elements inexplicably gravitate towards the edge of the page. Is there a specific reason for the suitcase (only log and pass)? <div class="control-group" ng-class="{true: 'error'}[submitted && form.log.$invalid]"> & ...