gpt4 book ai didi

javascript - Angular 4 无法读取未定义的属性 'category'

转载 作者:行者123 更新时间:2023-11-30 09:29:46 24 4
gpt4 key购买 nike

我又一次认为我对 Angular 4 缺乏理解!

我有一个页面,通过路由访问,我正在尝试通过 url-slug OnInit 获取帖子。帖子驻留在我从上一页(这是帖子列表页面)缓存的 Promise 数组中。列表页面工作正常。我所有的内容都缓存并从缓存中读取。我试过关闭它,出现同样的问题。

这是获取帖子的服务。

articles: Promise<Article[]>;

/**
* fetch a list of articles
*/
getArticles(): Promise<Article[]> {
// cached articles
if (this.articles) {
return this.articles;
}

// no articles fetched yet, go get!
return this.articles
= this.http.get(this.url, this.options)
.toPromise()
.then(response => response.json() as Article[])
.catch(this.handleError);
}


/**
* fetch a single article by url slug
* @param slug
*/
getArticle(slug: string): Promise<Article> {
return this.getArticles()
.then(articles => articles.find(article => article.slug == slug));
}

这就是在 SinglePost 组件上获取它的原因:

article: Article

ngOnInit(): void {
this.getArticle();
}

getArticle(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.articleService.getArticle(params.get('name')))
.subscribe(article => this.article = article);
}

html:

<a href="" class="post-cat  text-uppercase">{{ article.category }}</a>

帖子(我称之为文章)肯定存在,并且肯定正在从缓存中正常读取。

此外,尽管出现错误,但该页面实际上仍然显示正确的文章(因此我可以确认文章必须正确获取),所以我觉得它在填充之前尝试访问文章对象,我认为 Angular 会处理那个?

我的错误是:

ERROR TypeError: Cannot read property 'category' of undefined at Object.eval [as updateRenderer] (PostComponent.html:4) at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js?de3d:13105) at checkAndUpdateView (core.es5.js?de3d:12256) at callViewAction (core.es5.js?de3d:12599) at execComponentViewsAction (core.es5.js?de3d:12531) at checkAndUpdateView (core.es5.js?de3d:12257) at callViewAction (core.es5.js?de3d:12599) at execComponentViewsAction (core.es5.js?de3d:12531) at checkAndUpdateView (core.es5.js?de3d:12257) at callViewAction (core.es5.js?de3d:12599)

最佳答案

尝试使用 elvis 运算符 ?。:

<a href="" class="post-cat  text-uppercase">{{ article?.category }}</a>

仅当定义了 article 时,它才会访问 category 属性。

关于javascript - Angular 4 无法读取未定义的属性 'category',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com