Error: Attempting to access the 'libelle' property of an undefined value

Error: TypeError: Unable to read property 'libelle of undefined file:

this searche.html

import { Component,OnInit } from "@angular/core";
import { Router,NavigationExtras } from "@angular/router";
import observable = require("data/observable");
import { VoitureService } from "../../voiture/voiture.service";


@Component({
selector: "searche",
moduleId:module.id,
templateUrl: './searche.html',
providers: [VoitureService]

})
export class SearcheComponent {
    public constructor(private router:Router,private postsService:VoitureService) { 
}
voitures: voiture[];
clients:voiture;
req:string='1';
DT:Date;
idClient:number=0;
refClient:string="";
libelleClient:string;


ngOnInit(){
    this.postsService. getPosts(this.req)
        .subscribe(results => this.voitures=results );
}

public clicked(IDV:string,LDV:string,RDV:string){
    this.postsService. getClient(IDV)
        .subscribe(results => this.clients=results );
    this.libelleClient=this.clients.libelle;
    this.refClient=this.clients.ref;
    let navigationExtras: NavigationExtras = {
        queryParams:{
            libClient: this.libelleClient,
            refclient : this.refClient,

        }
    }
    this.router.navigate(["page1"], navigationExtras);
}
}


interface voiture{
id:number;
libelle:string;
ref:string;
}

this searche.html

<stackLayout  class="searcheview">
<stackLayout>

    <SearchBar class="input"  hint="Machine" ></SearchBar>
        <ListView [items]="voitures" >
            <ng-template let-voiture="item">
                <StackLayout   rows="auto, auto"  columns="*, auto" class="list-group-item"  (tap)="clicked(voiture.id,voiture.libelle,voiture.ref)">
                    <Label   text="{{ voiture.id }}" row="0" col="0"></Label> 
                    <Label   text="{{ voiture.libelle }}" row="0" col="0"></Label> 
                    <label text="{{ voiture.ref }} " row="1" col="0"></label>
                </StackLayout>
            </ng-template>
        </ListView>
</stackLayout>
</stackLayout>

Whenever the function clicked() is called, an error occurs saying TypeError: Cannot read property 'libelle' of undefined Please assist with a solution.

Answer №1

The reason for the error is clear - this.clients is currently undefined when you try to access it. This occurs because you are making an asynchronous call and need to perform your assignment within the subscribe method. The issue may be related to improper code formatting, making it difficult to read your code structure. It is advised to utilize proper indentation and avoid using shorthand syntax for callbacks and fallbacks.

For example:

public clicked(IDV: string, LDV: string, RDV: string) {
    this.postsService.getClient(IDV)
        .subscribe(results => {
            this.clients = results;

            this.libelleClient = this.clients.libelle;
            this.refClient = this.clients.ref;

            let navigationExtras: NavigationExtras = {
                queryParams: {
                    libClient: this.libelleClient,
                    refclient: this.refClient
                }
            }
        });
}

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 encountered while attempting to inject a store into a React application using Typescript

Currently, I am working on building a React app with TypeScript and using Redux for state management. However, I encountered an error related to the app component. https://i.sstatic.net/zetyR.png -app.tsx import React from 'react'; import { Pro ...

Encountering issues when attempting to invoke a function from an external file in Angular4

When attempting to call a method from an external file using Angular4, I am encountering the following error: Error: ERROR in src/app/about/about.component.ts(22,9): error TS2304: Cannot find name 'checkJS'. Below is the code I am working with ...

Using NavController.setRoot within a resolved Promise in an Ionic 2 application

I am currently facing an issue with navigating to another page after a successful login while using the JS Library with Parse Server. When I try to use this.navCtrl.setRoot(TemplatesPage);, it doesn't seem to have any effect in my application. After ...

Run a function from an alternate element

I have successfully created a grid with a button that enables me to control a timer. When I click on the start button in the grid on the home page, the timer begins counting the time. By using a service, I am able to determine whether the timer is active ...

Utilizing Webpack for Ahead-of-Time Compilation in Angular 4

Using Angular 4 and webpack 2, I attempted to implement AOT (Ahead Of Time compilation) but encountered the following error message: 10% building modules 4/5 modules 1 active ..._modules/intl/locale-data/jsonp/en.jsModuleNotFoundError: Module not found: Er ...

Retrieve an array that is returned from a function in TypeScript

In this function, I am trying to access the value of the 'value' array outside the function in the same class. This function is being called in a setter method where the ID is set like so: setId(id:string){ this.onChange(id)} class ModalShowComp ...

Access the value of an object field from an observable by utilizing the async pipe

I am interested in delving deeper into the use cases for the async pipe in Angular. The concept of having data asynchronously appear in the view simply by adding a pipe that subscribes to the data is quite appealing to me. However, I have primarily encou ...

Customizing hover effects for select field options

I need help customizing the background color of a dropdown menu when hovered over. I attempted to assign a class "page-limit-option" to the option element, but it didn't work. Should I create a new style component instead of using the option? <sele ...

How can we dynamically replace diagram.model in GoJS?

Is there a way to update the GoJS diagram on my webpage dynamically when new JSON data is fetched from a service? I tried triggering this change with an event like clicking a button, but I keep running into errors indicating that the div already has a di ...

Expanding a generic class by introducing a new generic parameter

I have a basic framework class: export class BaseClass< A extends boolean = false, B extends boolean = false, > { readonly fieldA: A; readonly fieldB: B; constructor(options: { readonly?: A, many?: B } = {}) { // @ts-ignor ...

What methods can I use to modify the text being shown in Angular HTML?

In my Angular template, I have 6 tabs being displayed: <tabset class="tabs"> <tab *ngFor="let option of options" [heading]="option.type" > <!-- tab content --> </tab> The heading for each tab is currently in a rather ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

Uh oh, there seems to be an issue with Angular 8 – it's throwing an error saying "TypeError: Cannot read

I created a website similar to Cat and Mash for selecting a cat at random, but I've encountered an error that is puzzling. Within my JSON object are URLs linking to images. My goal is to randomly display these images without repeating the same image ...

Typescript declaration for a .js file in a diverse project

Hey there! I'm currently in the process of converting my JavaScript React Redux project to TypeScript, and I've decided to kick things off by tackling my redux reducers file. Here's a snapshot of how my project is structured: Project/ .. ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

How can I assign a default value to a mat-select when the selection is determined by a function?

As a newcomer to Angular, I've encountered what seems like a simple challenge. I am attempting to set a default value for my mat-select to be the 'Active' option. When this option is selected, it triggers a function that filters a table for ...

The ButtonProps module is not compatible with the Button component within the same package

When working with Reactstrap, Typescript, and typings from @types/reactstrap, I encountered an issue while using the Button component in a Higher Order Component (HOC) that requires explicit reference to the ButtonProps type. Below is the code snippet: i ...

TypeScript throwing error: Attempting to call a potentially 'undefined' object goes against coding principles

In the snippet below, an error is encountered: example/not-following.ts:15:1 - error TS2722: Cannot invoke an object which is possibly 'undefined'. 15 run(true).maybe(); ~~~~~~~~~~~~~~~ Snippet: interface Example { maybe?: () => voi ...

Encountering a glitch with ng2-pdf-viewer on Angular version 13.2.2 and Ionic version 6

Issue reported: The following error message is encountered when trying to set up the PDF viewer: Error: Setting up fake worker failed: "Cannot load script at: https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.min.js". It is observed while ...

"Discover the method for calculating the length of a list where the 'read' attribute

My list looks like this: let chats: Chats[] = [ {id: 1, name: "James Anderson",read=false}, {id: 2, name: "James Anderson",read=true}, {id: 3, name: "James Anderson",read=true}, {id: 4, name: "James Anderson",read=true}, ] On my cshtml page, I have been ...