Angular 6 - 错误类型:TypeError: 无法读取未定义的属性"value"

8

我是一名新手,对于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;
                  } 
                }
            ); 
    }

}
3个回答

40

只需要使用

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

只有在API响应到达之前,您的joke对象才没有值。 因此,请使用?对空值进行检查,直到收到响应为止。


1
谢谢Prachi,你做得很好。我不会再忘记那个了。 - Steve Royall
我该如何解决动态对象的问题?我的HTML代码如下:<div>{{ joke['xyz' + index] }}</div>,在这里“?”解决方案不起作用。 - YasirPoongadan

5
您可以使用*ngIf在获取响应之前进行条件判断。
以下是示例:
<div *ngIf="joke">{{ joke.value }}</div>

1
在我的应用程序中注册后,需要立即更新个人资料。但是一开始model.address.postalCode为空。如果我使用<div *ngIf="model.address">,输入字段将不会显示。我该怎么办? - Denuka

-3

Angular 7 - 错误类型:TypeError:无法读取未定义的属性“value”

您可以使用?运算符检查对象值。

例如:

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

1
不管是什么,都不要抄袭。 - DevLoverUmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接