Html 未定义变量的角度字符串插值
我试图通过Angular的字符串插值在网页上显示从外部API获取的一些信息 当未提取任何信息或尚未“到达”时,我希望显示“不适用” 我尝试了以下方法,但我得到一个错误,即: 无法读取以下html代码第2行中未定义的属性“name” 在等待定义响应时,如何显示N/A app.component.html:Html 未定义变量的角度字符串插值,html,angular,typescript,Html,Angular,Typescript,我试图通过Angular的字符串插值在网页上显示从外部API获取的一些信息 当未提取任何信息或尚未“到达”时,我希望显示“不适用” 我尝试了以下方法,但我得到一个错误,即: 无法读取以下html代码第2行中未定义的属性“name” 在等待定义响应时,如何显示N/A app.component.html: {{!!this.apinfo.name?this.apinfo.name:'N/A'} app.component.ts: 从'src/app/apinfo.model'导入{apinfo
{{!!this.apinfo.name?this.apinfo.name:'N/A'}
app.component.ts:
从'src/app/apinfo.model'导入{apinfo}
从'src/app/api.service'导入{ApiService}
(...)
@组成部分({
选择器:'应用程序根',
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent实现OnInit、OnDestroy{
apinfo:apinfo;
apiInfoSub:订阅;
构造函数(apiService:apiService){}
恩戈尼尼特(){
//apiService.apinfo是存储API响应的主题
this.apinfo sub=this.apiService.apinfo.subscribe(
(回应)=>{
this.apinfo=响应;
}
);
}
恩贡德斯特罗(){
this.apinfo.sub.unsubscribe();
}
}
apinfo.model.ts:
导出类apinfo{
公共名称:string,
公众id:号码,
构造函数(名称:字符串,id:编号){
this.name=名称;
this.id=id;
}
}
请将您的app.component.html
更改为以下内容:
<div id="api-info">
{{ apiInfo?.name ? apiInfo.name : 'N/A' }}
</div>
{{apinfo?.name?apinfo.name:'N/A'}
这应该可以解决问题。
apinfo
在开始时未定义。订阅不会立即解析,因此在一段时间后设置apinfo=response
。可能使用
或者在声明时初始化:
apinfo:apinfo={}代码>我建议不要在组件内订阅。最好使用异步管道,并检查如下
<div id="api-info" *ngIf="(apiInfo$ | async as apiInfo); else pending">
{{ apiInfo.name }}
</div>
<ng-template #pending>
n/a
</ng-template>
{{apinfo.name}
不适用
这还允许您以不同的方式设置n/a,非常简单最好使用异步管道,而不是手动订阅和取消订阅流。这使代码更清晰,并在html中使用表达式:
{{(stream$|async)?.name || 'N/A'}}
下面是代码示例: