Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...