无法读取未定义角度4的属性“名称" [英] Cannot read property 'name' of undefined angular 4

查看:69
本文介绍了无法读取未定义角度4的属性“名称"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在组件模板中打印一个值.

I am trying to print a value in the template of component.

但是我遇到了以上错误 Cannot read property 'name' of undefined

But I am getting the above error Cannot read property 'name' of undefined

我已从代码中删除了此问题的多余内容.我要访问详细信息的第一行.

I have removed the extra contents from code for this question. I want to access the first row of the details.

组件文件

import {
  Component
} from '@angular/core';
import {
  Person
} from './person';
import {
  getPersonDetailsService
} from './person.service';

@Component({
  selector: 'my-app',
  template: `
      {{data[0].name}}
      `
})
export class AppComponent {
  data: Person[] = [];
  ngOnInit(): void {
    this.getPersonDetailsService.getData()
      .then(data => this.data = data.slice(1, 5));
  }

}

推荐答案

我认为您应该先检查在浏览器中打印数据时是否定义了数据.

I think you should first check if data is defined when you print it in browser.

{{data[0]?.name}}

由于最初没有定义数据,因此无法访问其name属性.

As your data is not defined initially, you cannot access the name property of it.

文档

Angular安全导航操作员(?.) 防止属性路径中的空值和未定义值的方法.这里 是的,如果currentHero为 空.

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

您还可以使用&&条件检查变量是否为空

You can also check if the variable is null or not by using && condition

{{data[0] && data[0].name}}

这篇关于无法读取未定义角度4的属性“名称"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆