json - 如何正确显示对象数据以在 Angular 2 中查看

标签 json angular angular2-template typescript-typings

我正在学习 Angular 2,我无意中发现了一种奇怪的观点。

在我的 ts 代码中,我有:

import { CompanyService } from '../../services/company.service';
import { Company } from '../../models/company';    
export class TestEssayComponent implements OnInit {
        company: Company;
        constructor(private companyService: CompanyService){}
    ngOnInit() {
        this.getCompany();
      }
    getCompany(){
        var company_id: number;
        company_id = parseInt(localStorage.getItem('company_id'));
        this.companyService.getById(company_id).subscribe(
          data => {
            var company = new Company;
            company = data.data;
            this.company = company;
            console.log(this.company);
          }
        );
     }
}

在 html 文件中我有:

<section class="content-header">
    <h1>New Test <small>{{company.name}}</small></h1>
</section>

然后这会给出错误“name of undefined”,但是当我将其替换为:

<section class="content-header">
        <h1>New Test <small>{{company}}</small></h1>
    </section>

这将显示[object Object]。并且在控制台中,数据被填充。 那么如何在 View 中正确显示呢?

最佳答案

在数据尚不可用时,使用安全导航运算符?.来防范nullundefined

<h1>New Test <small>{{company?.name}}</small></h1>

您还可以使用*ngIf,例如

<h1 `*ngIf="company">New Test <small>{{company.name}}</small></h1>

仅在数据可用后渲染元素。

关于json - 如何正确显示对象数据以在 Angular 2 中查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42482941/

相关文章:

json - 用 "For Loop"填充矩阵花费的时间太长

angular - 语法正确的复数/单数结尾

javascript - 带有@HostListener的Angular 4加载事件

javascript - 在 angular2 中,如何检测是否有 ng-content?

css - Angular 2 外部样式没有内联到标题

java - 在JAVA中生成JSON

javascript - 如何在 Asp.net MVC 中使用 Json 字符串初始化 javascript 变量?

javascript - 单击按钮时获取新的 JSON 对象 (jQuery)

linux - 如何将端口 4200(Angular Web 服务器)绑定(bind)到端口 80(Apache Web 服务器)?

javascript - ngModel 无法正确检测数组更改