Angular 6-错误TypeError:无法读取未定义的属性“值" [英] Angular 6 - ERROR TypeError: Cannot read property 'value' of undefined
问题描述
我是Angular和Typescript的新手,无法触到此控制台错误的底部:"ERROR TypeError:无法读取未定义的属性'value'"
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"
我正在打电话给一个愚蠢的服务,该服务返回了Chuck Norris的笑话.这实际上可以.但是,我遇到Typescript控制台错误.
I'm calling a silly service that returns a Chuck Norris joke. This actually works OK. I'm getting Typescript console errors however.
我在这里转载: https://stackblitz.com/edit/angular-chuck
非常感谢您的光临.
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;
}
}
);
}
}
推荐答案
只需使用
<div>{{ joke?.value }}</div>
在API响应到达之前,您的joke
对象没有该值.因此,使用?
进行空检查,直到响应到达.
Your joke
object doesn't have the value until the API response arrives. Thus use ?
to apply the null check until the response arrives.
这篇关于Angular 6-错误TypeError:无法读取未定义的属性“值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!