无法读取angular2中未定义的属性"title"

编程入门 行业动态 更新时间:2024-10-27 04:35:03
本文介绍了无法读取angular2中未定义的属性"title"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的组件

export class MoviedetailComponent implements OnInit { movie:any constructor( private getmovie: GetmovieService, private router: Router, private rout: ActivatedRoute ) { } ngOnInit() { this.rout.params .switchMap((params: Params) => this.getmovie.getMovieById(+params['id'])) .subscribe(movie => { this.movie = movie; console.log(this.movie); }); } }

我的html

<p>{{movie.title}}</p>

因此,当我加载页面时,它会显示movie.tittle的内容,但是控制台中还会显示一个错误,提示无法读取未定义的属性'title'".

So when I load the page, it shows the content of movie.tittle, but there is also an error in console saying "Cannot read property 'title' of undefined"

有什么想法吗?

推荐答案

subscribe()函数是异步的,这意味着可以在ngOnInit()方法完成之后执行回调(包括this.movie = movie)内部的代码.

The subscribe() function is asynchronous, meaning the code inside of the callback (including this.movie = movie) can be executed after the completion of the ngOnInit() method.

正如@kirk和@jonrsharpe在评论中指出的那样,您可以在模板内部的值之前添加一个测试.但这不是最优雅的解决方案.

As @kirk and @jonrsharpe pointed out in the comments, you could add a test before the value inside of the template. But this is not the most elegant solution.

我建议改为阅读Observables,尤其是异步管道.这使您的代码更加简单:

I would suggest instead reading up on Observables, and in particular, the async pipe. This makes your code a lot simpler:

this.movie = this.route.params .switchMap((params: Params) => this.getmovie.getMovieById(+params['id']))

,然后您的HTML将如下所示:

and then your HTML would look like:

<p>{{ (movie | async)?.title }}</a>

请注意?-这将检查title属性是否确实存在,因此如果对象无效,则不会发生错误.您还应该在其他地方添加模板块,以处理错误情况.

Note the ?- this checks that the title property actually exists, so that an error doesn't occur if the object is invalid. You should also add a template block somewhere else which handles cases of errors.

更多推荐

无法读取angular2中未定义的属性"title"

本文发布于:2023-11-22 23:15:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619298.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   中未   定义   quot   title

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!