在我的服务中,我正在向后端提供JSON数据。(本地系统的JSON文件(
加载后,我在页面中看到了值。但也出现错误。似乎甚至在我的数据可用之前,我的模板都试图获取值。
如何防止这个问题?这是我的组件代码:
import { Component, OnInit } from '@angular/core';
import { ServerService } from './shared/service/server.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
data:Object;
constructor(private server:ServerService){}
ngOnInit(){
this.server.getJSON().subscribe(data => this.data = data );
}
}
这是错误:我看到3次的错误。页面也使我的价值也
AppComponent.html:2 ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer] (AppComponent.html:2)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
at checkAndUpdateView (core.js:13849)
at callViewAction (core.js:14195)
at execComponentViewsAction (core.js:14127)
at checkAndUpdateView (core.js:13850)
at callWithDebugContext (core.js:15098)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14635)
at ViewRef_.detectChanges (core.js:11619)
at eval (core.js:5918)
访问模板中使用的名称。
<div *ngIf="data?.name">
而不是写作 data:object; 写 data:object = {};
在这种情况下,数据将是一个不再不确定的新对象。
另一种方式是在
的oninit函数中进行新的you reboctngOnInit(){
this.data = {};
this.server.getJSON().subscribe(data => this.data = data );
}
基本上您可以使用NGIF,直到数据可用
<div *ngIf="data">
{{data.name}}
</div>
编辑:另一种使用方法是使用加载标志
data:Object;
dataLoading=true;
constructor(private server:ServerService){}
ngOnInit(){
this.server.getJSON().subscribe(data =>{
this.data = data
this.dataLoading = false;
});
}
<div *ngIf="!dataLoading ">
{{data.name}}
</div>
您可能正在阅读HTML中的.name
。我认为这将是改变诺言中的职能的最佳实践,然后您可以尝试使用以下方式:
async ngOnInit(){
this.data = await this.server.getJSON();
}
,更具体地说,最好初始化数据对象。例如,如果您仅阅读name
属性,则可以执行此操作:
public data: any;
constructor() {
this.data = {name: null}
}