无法读取未定义的属性“标题",但显示标题 [英] Cannot read property 'title' of undefined, but title is displayed

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

问题描述

我是angular 4的新手,我正在尝试构建我的第一个应用程序.

标题显示在屏幕上,但在控制台中出现此错误:

这是html文件中的第26行:

<h1>{{result.title}}</h1>

这是 TravelDetailComponent :

export class TravelDetailComponent implements OnInit {

result: string[];
id: number;

constructor(private http: Http, private globals: Globals, private activatedRoute: ActivatedRoute) {
}


ngOnInit() {
  this.activatedRoute.params.subscribe((params: Params) => {
      this.id = params['id'];
      console.log(this.id);
  });
  this.http.get(this.globals.baseUrl + 'travels/' + this.id)
      .map(res => res.json()).subscribe(result => this.result = 
result);
}

}

为什么标题显示在屏幕上,但是我在控制台中收到此错误,我该如何解决呢?

解决方案

除非您熟悉角度模板语法.特别是*ngIf和Elvis运算符?的使用.

例如,如果您只想显示标题,则可以执行以下操作以确保页面在标题出现之前不要尝试呈现标题.

<h1 *ngIf="title">{{ title }}</h1>

此外,如果您有一个带有属性的对象,则可以放弃*ngIf并检查以确保该对象已解析.例如,假设您将页面的所有数据保存到page对象中,并且像上面一样,想要显示标题.

<h1>{{ page?.title }}</h1>

如果您想真正安全,仍可以将其包装在*ngIf语句中,以专门检查标题,但是通常,如果您在page对象中包含数据,则可以安全地假定其中有一个标题./p>

I'm new with angular 4 , and I'm trying to build my first application.

The title is displayed in the screen but get this error in the console :

This is line 26 in the html file:

<h1>{{result.title}}</h1>

This is TravelDetailComponent:

export class TravelDetailComponent implements OnInit {

result: string[];
id: number;

constructor(private http: Http, private globals: Globals, private activatedRoute: ActivatedRoute) {
}


ngOnInit() {
  this.activatedRoute.params.subscribe((params: Params) => {
      this.id = params['id'];
      console.log(this.id);
  });
  this.http.get(this.globals.baseUrl + 'travels/' + this.id)
      .map(res => res.json()).subscribe(result => this.result = 
result);
}

}

why the title is displayed in the screen but I get this error in the console and how can I solve it ?

解决方案

You'll run into this A TON in angular unless you familiarize yourself with the Angular Template Syntax. Specifically the use of the *ngIf and the elvis operator ?.

For example, if you are just wanting to display the title you could do the following to make sure the page doesn't try to render the title until it has one.

<h1 *ngIf="title">{{ title }}</h1>

Furthermore if you have an object with a property you can forgo the *ngIf and check to make sure the object has resolved. For instance let's say you save all of the page's data into the page object and like above, want to display the title.

<h1>{{ page?.title }}</h1>

If you wanted to be really safe, you could still wrap it in an *ngIf statement that checks the title specifically, but usually if you have data within the page object, it's safe to assume there's a title in there.

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

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