无法读取angular2中未定义的属性"title" [英] Cannot read property 'title' of undefined in angular2
问题描述
我的组件
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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!