I am trying to display some information which is fetched from an external API on a web page by using Angular's string interpolation.
When no information is fetched or hasn't "arrived" yet, I want to display '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.
How can I show N/A while waiting for the response to be defined?
app.component.html:
<div id="api-info">
{{ !!this.apiInfo.name ? this.apiInfo.name : 'N/A' }}
</div>
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:
export class ApiInfo {
public name: string,
public id: number,
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}