角度6-错误TypeError:无法读取未定义的属性“值”

时间:2018-08-01 11:41:49

标签: angular typescript

我是Angular和Typescript的新手,无法触及此控制台错误的底部:“ ERROR TypeError:无法读取未定义的属性'value'”

我打电话给一个愚蠢的服务,该服务返回了Chuck Norris的笑话。这实际上可以。但是,我遇到Typescript控制台错误。

我在这里转载: one of the answers

非常感谢您的光临。

data.service.ts

+----+-------------+----------+-------+----------------------------------+----------+---------+------+------------+----------------------------------------------+
| id | select_type | table    | type  | possible_keys                    | key      | key_len | ref  | rows       | Extra                                        |
+----+-------------+----------+-------+----------------------------------+----------+---------+------+------------+----------------------------------------------+
|  1 | SIMPLE      | prod_val | index | PRIMARY,value_id,product_fitment | value_id | 4       | NULL | 1499189079 | Using index; Using temporary; Using filesort |
+----+-------------+----------+-------+----------------------------------+----------+---------+------+------------+----------------------------------------------+

data.model.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.component

 export class DataModel {
    public category: any;
    public icon_url: string;
    public id: string;
    public url: string;
    public value: string;
}

3 个答案:

答案 0 :(得分:16)

只需使用

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

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

答案 1 :(得分:4)

您可以使用* ngIf直到得到重新操作

下面是示例

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

答案 2 :(得分:0)

角度7-错误TypeError:无法读取未定义的属性'value'

您可以使用#include <iostream> #include <optional> int main() { std::optional<int> array[5]; array[2] = 23; array[4] = 0; for (int i = 0; i < 5; ++i) { if (array[i]) { std::cout << "in array" << std::endl; } else { std::cout << "not in array" << std::endl; } } } 运算符检查对象值。

示例:

?