角度:看不懂的未定义的属性,但仍显示数据

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

我很困惑,因为我的应用程序是显示必要的数据,但仍有在控制台的错误,我想摆脱。

打字稿:

  activeClient: Client;

  constructor(private clientService: ClientService) { }

  ngOnInit() {
    this.inViewMode = true;
    this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
    this.clientService.getClientById(this.clientId)
        .subscribe(data => this.activeClient = data);
  }

HTML:

<div class="form-row">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

客户端模式:

export interface Client {
    id?: number;
    companyName?: String;
    firmRegNo?: number;
    address?: String;
    clientName?: String;
    phoneOne?: number;
    phoneTwo?: number;
    email?: String;
    explanation?: String;
    rating?: number;
    status?: String;
    clientContract?: ClientContract;
}
angular
3个回答
1
投票

使用safe navigation operator防止错误,直到activeClient初始化:

[value]="activeClient?.companyName"

2
投票

由模板被渲染的时候,activeClient不存在(等待可观察到拉数据)。使用elvis运营安全显示。

[value]="activeClient?.companyName"


2
投票

你通过进行activeClient调用的API获得了async值。您的模板不会等待那个被定义的,直到现在。因此你要在控制台上的错误。

只要activeClientsubscribe块初始化,你看到的价值。

为了避免这种情况,直到activeClient初始化不呈现模板。

由于activeClient有很多领域,我推荐使用*ngIf

<div class="form-row" *ngIf="activeClient">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

或者,你也可以在模板中使用的async管:

activeClient$: Observable<Client>;

constructor(private clientService: ClientService) {}

ngOnInit() {
  this.inViewMode = true;
  this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
  this.activeClient$ = this.clientService.getClientById(this.clientId);
}

而在你的模板:

<div class="form-row" *ngIf="activeClient$ | async as activeClient">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.