【问题标题】:Angular 5 console errors happening before data is returned to the page from service , how can this be prevented?在数据从服务返回到页面之前发生 Angular 5 控制台错误,如何防止这种情况发生?
【发布时间】:2018-07-09 22:34:04
【问题描述】:

问题:我在 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;
        })
}

【问题讨论】:

  • 使用caseCaption?.CaseDisplayNumber
  • 您忘记将 this.model 输入到 getPageCommonData 函数中
  • @HarryNinh 哇哦,我们这样行吗?你能写一个快速的答案吗?谢谢!
  • Azzi 的很全面,标记一下! :)

标签: javascript angular typescript http-post angular-services


【解决方案1】:

您可以更改以下代码行:

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

选项 1:

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

选项 1 使用 ? 称为“二元运算符”或“猫王运算符”;如果该操作数为真,则返回其第一个操作数。在这种情况下,“Elvis Operator”会通知模板需要显示的对象可能尚不可用,并允许模板继续呈现。对象可用时呈现对象及其值。

See this article.

选项 2:

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

来自@Brad 它被称为安全导航运算符。很清楚 在文档中说明 angular.io/guide/template-syntax#expression-operators。

【讨论】:

猜你喜欢
  • 2021-12-20
  • 1970-01-01
  • 2020-04-26
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多