[英]Angular - String interpolation of undefined variable
I am trying to display some information which is fetched from an external API on a web page by using Angular's string interpolation.我正在尝试使用 Angular 的字符串插值在网页上显示从外部 API 获取的一些信息。
When no information is fetched or hasn't "arrived" yet, I want to display 'N/A'.当未获取任何信息或尚未“到达”时,我想显示“N/A”。
I have tried the following approach, however I get an error saying: 'Can't read property 'name' of undefined' on line 2 of the following html code.我尝试了以下方法,但是我收到一条错误消息:“无法读取以下 html 代码第 2 行的未定义属性‘名称’”。
How can I show N/A while waiting for the response to be defined?如何在等待定义响应时显示 N/A?
app.component.html: app.component.html:
<div id="api-info">
{{ !!this.apiInfo.name ? this.apiInfo.name : 'N/A' }}
</div>
app.component.ts: app.component.ts:
import { ApiInfo } from 'src/app/apiInfo.model'
import { ApiService } from 'src/app/api.service'
(...)
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
apiInfo: ApiInfo;
apiInfoSub: Subscription;
constructor(apiService: ApiService) {}
ngOnInit() {
// apiService.apiInfo is a Subject<ApiInfo> where the API response is stored
this.apiInfoSub = this.apiService.apiInfo.subscribe(
(response) => {
this.apiInfo = response;
}
);
}
ngOnDestroy() {
this.apiInfoSub.unsubscribe();
}
}
apiInfo.model.ts: apiInfo.model.ts:
export class ApiInfo {
public name: string,
public id: number,
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
I suggest to not subscribe within the component.我建议不要在组件内订阅。 Better use the async pipe instead and check as follows...
最好使用异步管道代替并检查如下...
<div id="api-info" *ngIf="(apiInfo$ | async as apiInfo); else pending">
{{ apiInfo.name }}
</div>
<ng-template #pending>
n/a
</ng-template>
Which also allows you to style the n/a differently quite easy这也使您可以轻松地为 n/a 设置不同的样式
please change your app.component.html
to below:请将您的
app.component.html
更改为以下内容:
<div id="api-info">
{{ apiInfo?.name ? apiInfo.name : 'N/A' }}
</div>
this should resolve the issue.这应该可以解决问题。
apiInfo
is undefined at start. apiInfo
在开始时未定义。 The subscribe does not resolve immediately, so the apiInfo = response
is set after some time.订阅不会立即解析,因此
apiInfo = response
会在一段时间后设置。 Maybe use <div id="api-info" *ngIf="apiInfo">
也许使用
<div id="api-info" *ngIf="apiInfo">
Or initialize on declaration: apiInfo: ApiInfo = <ApiInfo>{};
或者在声明时初始化:
apiInfo: ApiInfo = <ApiInfo>{};
It is better to use async pipe, instead of subscribing and unsubscribing to stream manually.最好使用异步管道,而不是手动订阅和取消订阅流。 That makes the code cleaner and in the html use expression:
这使代码更清晰,并在 html 中使用表达式:
{{(stream$|async)?.name || 'N/A'}}
Here is code sample: https://stackblitz.com/edit/angular-nknwuq这是代码示例: https : //stackblitz.com/edit/angular-nknwuq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.