我是一名新手,对于Angular和Typescript还不熟悉,但我无法解决这个控制台错误:"ERROR TypeError: Cannot read property 'value' of undefined"。
我调用了一个返回Chuck Norris笑话的愚蠢服务。实际上这个服务可以正常工作,但我仍然会得到Typescript控制台错误。
我在这里重现了这个问题: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;
}
}
);
}
}