Uncaught TypeError: Cannot read property ‘id’ of undefined

Mohammad Hassani
2 min readMar 9, 2021

--

Comman Angular fatal error “Uncaught TypeError: Cannot read property ‘id’ of undefined”

Uncaught TypeError: Cannot read property ‘id’ of undefined

It is common that object be come null value, for example when your application tocken access expire and the user must login agian with popupp login form that user stay on same page that he was.In the current component you are reading an objects property that needs to be loaded first from database but when the session is renewed,component will init and your object is null so the browser will throw an unresolved error, Fatal Error, and it is not good att all to your application.

Let see my solution in Angular that can be used to other Javascript and Typescript framworks too.

ngOnInit() {

this.id= this.appService.object.id //you have a service that is reading a object and here you want to use its property but the object is null here

this.loadData(this.id)

}

private loadData() {

this.service.gets().subscribe(

result=> {console.log(result)},

error => {console.log(error)}

);}

}

When the app try to init the component you will get Fatal error that says “Uncaught TypeError: Cannot read property ‘id’ of undefined” it is a bug in the system and when the user try to click on “OK” the application will be reloaded and as your code, he will come back to the this component, this loop error crashes the app.

My solution how to hundel this error

Try and Catch is the solution but not in each place that you have the same situation, Writing a function in to a service will handel all the same situations.

ChackValue(value:any){

try {

return value();

} catch (error) {

console.log(error);

this.router.navigate([‘/’]) // or logout the user and redirect to the function to read the object first

}

}

And then use it in you component

ngOnInit() {

this.id=this.ChackValue(()=> this.appService.object.id )// if the object is null or undefined så you can see the error in console and app will not crash.

this.loadData(this.id)

}

Hope this help…

--

--