8

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;
                  } 
                }
            ); 
    }

}
0

3 Answers 3

40

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Prachi, you nailed it. I'll not forget that one again.
how i can solve this issue in dynamic object ?, my html look like this <div>{{ joke['xyz' + index] }}</div>, '?' solution not works here
5

You can use *ngIf until getting resopnse

below is the sample,

<div *ngIf="joke">{{ joke.value }}</div>

1 Comment

Immediately after register into my application, need to update profile data. But in the beginning the model.address.postalCode is null. If i use <div *ngIf="model.address">, input filed will not display. What can I do for that ?
-3

Angular 7 - ERROR TypeError: Cannot read property 'value' of undefined

You can check for the object value by using the ? operator.

Example:

<div> {{ joke?.value }} </div>

1 Comment

copy-cat what so ever

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.