Angular 在数据从服务返回到页面之前发生了 5 个控制台错误,如何防止这种情况发生?

Angular 5 console errors happening before data is returned to the page from service , how can this be prevented?

问题:我在 chrome 浏览器 F12 开发工具

中看到几个错误

我看到这个大约 8 次

  ERROR TypeError: Cannot read property 'CaseDisplayNumber' of undefined

HTML 导致此错误的模板页面

<span class="header-data">{{caseCaption.CaseDisplayNumber}}</span>

在这些错误下我确实看到了

 this.caseCaption  {CaseDisplayNumber: "CR2017129322000", 

所以这似乎是通话时间问题?

HTML 代码输出看起来很好...

组件

    ngOnInit(): void {

              this.pageService.getPageCommonData(this.model) //(this.model)
                        .subscribe(
                        result => {
                                   this.caseCaption = result["data"].CaseCaptionInfo;

                       }
            }

服务

getPageCommonData(menu: Menu)  {
        return this.http.post(pageCommonData, JSON.stringify(menu), httpOptions)
        .map((response: Response)=> {

            return response;
        })
}

您可以更改以下代码行:

<span class="header-data">{{caseCaption.CaseDisplayNumber}}</span>

选项 1:

<span class="header-data">{{caseCaption?.CaseDisplayNumber}}</span>

选项1使用?称为'Binary Operator'或'Elvis Operator';如果该操作数为真,它 returns 它是第一个操作数。在这种情况下,'Elvis Operator' 通知模板需要显示的对象可能还不可用,并允许模板继续渲染。对象可用时呈现对象及其值。

See this article.

选项 2:

<span *ngIf="caseCaption" class="header-data">{{caseCaption.CaseDisplayNumber}}</span>

From @Brad It's called the Safe Navigation Operator. Very clearly stated in the docs angular.io/guide/template-syntax#expression-operators.