Angular 4不显示数据

问题描述 投票:-1回答:1

我正在尝试将我的组件中的一些数据显示到html。令我感到困惑的是,在较旧的组件文件中,这有效。现在,在我创建的一些新的中,它只在登录并刷新页面后才开始工作。

我的component.ts文件:

import {Component} from '@angular/core';
import {DataService} from '../../services/data.service';
import {ActivatedRoute, Router} from '@angular/router';
import * as $ from 'jquery/dist/jquery.min.js';
import 'jquery-ui/jquery-ui.min.js';

declare let jQuery: any;

@Component({
  templateUrl: '../../templates/plan/general-info.html',
})
export class GeneralInfoComponent {

  data;
  selectedCompany = null;
  selectedPlace = null;

  constructor(private dataService: DataService,
              private router: Router,
              private route: ActivatedRoute) {
    this.data = this.route.parent.snapshot.data;
    this.selectedCompany = this.data.companies[0];
    this.selectedPlace = this.dataService.selectedPlace.getValue();
  }
}

我的模板文件令人不安的部分:

<div class="general-data">
  <h3>{{selectedCompany.name}}</h3>
  <h3>Reg nr {{selectedCompany.regCode}}</h3>
  <h3>{{selectedCompany.address}}</h3>
  <h3>{{selectedCompany.phone}}</h3>
  <h3>{{selectedCompany.email}}</h3>
  <h3>{{selectedCompany.contactPerson}}</h3>
  <h3>{{selectedCompany.personCode}}</h3>
</div>
<div class="general-data">
  <h3>{{selectedPlace.name}}</h3>
  <h3>{{selectedPlace.address}}</h3>
  <h3>{{selectedPlace.contactPerson}}</h3>
  <h3>{{selectedPlace.phone}}</h3>
  <h3>{{selectedPlace.email}}</h3>
  <h3>{{selectedPlace.personCode}}</h3>
</div>

我不想写另一个hack来用jQuery显示数据。奇怪的是,刷新后数据很好地显示,就像我第一次加载页面时没有得到数据一样。这样的事情甚至可能吗?

注意:在为this.selectedCompany和this.selectedPlace赋值后立即记录数据时,它会在控制台中显示正确的信息。

我的问题:如何让它直接运行而不必刷新页面?

我一整天都在搞乱这一点,并且会喜欢解决方案。

提前致谢。

angular
1个回答
0
投票

使用 ”?。” (安全导航操作符)在所有表达式中的对象之后。如下。

{{selectedCompany?.name}}

链接 - https://angular.io/guide/template-syntax#expression-operators

© www.soinside.com 2019 - 2024. All rights reserved.