I'm new to Angular and Typescript and cannot get to the bottom of this console error: "ERROR TypeError: Cannot read property 'value' of undefined"
I'm calling a silly service that returns a Chuck Norris joke. This actually works OK. I'm getting Typescript console errors however.
I've reproduced here: https://stackblitz.com/edit/angular-chuck
Many thanks for looking.
data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DataModel } from './data.model';
@Injectable()
export class DataService {
constructor( private http: HttpClient ) { }
chuckUrl = 'https://api.chucknorris.io/jokes/random';
getChuck() {
return this.http.get<DataModel>(this.chuckUrl);
}
}
data.model.ts
export class DataModel {
public category: any;
public icon_url: string;
public id: string;
public url: string;
public value: string;
}
data.component
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { DataModel } from './data.model';
@Component({
selector: 'app-data',
templateUrl: './data.component.html'
})
export class AppData implements OnInit {
constructor(private dataService: DataService) { }
joke: DataModel;
ngOnInit() {
this.dataService.getChuck()
.subscribe(
(data: DataModel ) => {
if (data.category != 'explicit') {
this.joke = data;
}
}
);
}
}
Add undefined check on variable To fix the “cannot read property of undefined” error, check that the value is not undefined before accessing the property. For example, in this code: const auth = undefined; console. log(auth); // undefined // TypeError: Cannot read properties of undefined (reading 'user') console.
Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined .
The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.
The "Cannot read Property '0' of undefined" error occurs when accessing an undefined value at index 0 . To solve the error, initialize the variable to the correct data type, e.g. array or string, before accessing the index.
Just use
<div>{{ joke?.value }}</div>
Your joke
object doesn't have the value until the API response arrives. Thus use ?
to apply the null check until the response arrives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With