我有一个Angular应用程序,它使用ngx-translate包来转换静态字符串。该值显示在前端,该属性也在json文件中。出于一个奇怪的原因,只有一个组件会将此错误抛出3次:
ng:///HomeModule/NewestFeatureComponent.ngfactory.js:19 ERROR TypeError: Cannot read property 'title' of undefined
at Object.eval [as updateRenderer] (ng:///HomeModule/NewestFeatureComponent.ngfactory.js:34)
at Object.debugUpdateRenderer [as updateRenderer] (vendor.js:89449)
at checkAndUpdateView (vendor.js:88486)
at callViewAction (vendor.js:88846)
at execComponentViewsAction (vendor.js:88774)
at checkAndUpdateView (vendor.js:88487)
at callViewAction (vendor.js:88846)
at execComponentViewsAction (vendor.js:88774)
at checkAndUpdateView (vendor.js:88487)
at callViewAction (vendor.js:88846)
最新-feature.component
import { Component, OnInit } from '@angular/core';
import { BlogBox } from 'src/models/blog-box';
import { BlogService } from 'src/app/blog/blog.service';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
@Component({
selector: 'app-newest-feature',
templateUrl: './newest-feature.component.html',
styleUrls: ['./newest-feature.component.scss']
})
export class NewestFeatureComponent implements OnInit {
post: BlogBox;
constructor(private readonly bs: BlogService, private translate: TranslateService) {
this.getLastUpdatesPost();
// Subcribe to language change to fetch the posts again
translate.onLangChange.subscribe((event: LangChangeEvent) => {
this.getLastUpdatesPost();
});
}
getLastUpdatesPost() {
this.bs.getLastUpdatesPost(this.translate.currentLang).subscribe(res => {
this.post = res;
});
}
ngOnInit() {
}
}
最新-feature.html
<div id="newestFeature" class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-12 col-sm-6 order-last order-sm-first post-image">
<img src="{{post?.img}}" alt="">
</div>
<div class="col-12 col-sm-5 offset-sm-1 order-first order-sm-last post">
<h5>{{'newestFeature.title' | translate}}</h5>
<h3 [innerHTML]="post.title"></h3>
<h4>{{post.featuredCategory}}</h4>
<h4> <span [innerHTML]="post.date | date: ' __ MMMM / yyyy' | formatDateSelector"> </span></h4>
<p [innerHTML]="post.content"></p>
<!-- <a href="updates/"><button class="button button-pink-orange">Összes fejlesztés</button></a> -->
</div>
</div>
</div>
</div>
</div>
hu.json
{
"newestFeature": {
"title": "Legfrissebb fejlesztésünk"
}
}
在任何人对elvis操作员说什么之前,它不能用于这个管道
此错误与:post.title
有关。
这意味着在post
设置之前:
this.bs.getLastUpdatesPost(this.translate.currentLang).subscribe(res => {
this.post = res;
});
它没有价值,因此未定义。
你应该在html中使用?
,如下所示:
post?.title
你可以在这里更多地阅读这个:https://blog.fullstacktraining.com/question-mark-in-angular-expression/
另一个解决方案,如果你想避免使用?
运算符就是在这里使用* ngIf:
<div class="row" *ngIf="post">