我想运行这段简单的代码,基本上它会根据状态(字符串)更改标签和图标
<ng-container *ngIf="container.length > 0">
<span *ngIf="!container.status.includes('Paused') && container.status.includes('Up')"
class="label label-success label-lg-status"><span class="fa fa-check"></span> Completed - {{ container.status }}</span>
<span *ngIf="container.status.includes('Paused')" class="label label-warning label-lg-status"><span
class="fa fa-pause"></span> Completed - {{ container.status }}</span>
<span *ngIf="container.status.includes('Exited')" class="label label-danger label-lg-status"><span
class="fa fa-stop"></span> Completed - {{ container.status }}</span>
</ng-container>
但是我收到一个错误,说不能使用包含null,所以我放*ngIf="container.length > 0"
现在我得到ReportComponent.html:22 ERROR TypeError: Cannot read property 'length' of null
如何让html等待执行get请求?
export class ReportComponent implements OnInit {
private containerName:string;
private processes = [];
private container = [];
private settings = [];
private environment = [];
private id:Number;
constructor(private _route:ActivatedRoute, private dockerService:DockerService, private environmentService:EnvironmentService, private settingsService:SettingsService) { }
ngOnInit() {
// Get Environment id
this._route.params.subscribe(params => {
this.id = params['id'];
// Get Environment
this.environmentService.getEnvironment(this.id).subscribe( environment => {
this.environment = environment;
console.log(environment);
//this.containerName = this.environment.name;
});
// Get Docker processes
this.dockerService.getProcesses(this.containerName).subscribe(processes => {
this.processes = processes;
});
// Get Docker Container Object
this.dockerService.getContainer(this.containerName).subscribe( container => {
this.container = container;
});
// Get Settings
this.settingsService.getSettings().subscribe( settings => {
this.settings = settings;
});
});
}
}
答案 0 :(得分:1)
使用它像:
*ngIf="container && (container.length > 0)"
错误将被删除。
除非length
数组可用,否则不会检查container
。
答案 1 :(得分:1)
是的可以像这样使用它,它会更加Angular方式
<ng-container *ngIf="container?.length > 0">
它也会起作用。
答案 2 :(得分:0)
您确切的问题是服务调用是异步的。因此,DOM绑定在
container
对象中绑定值之前启动。因为DOM呈现不等待异步服务响应的完成
解决方法是,你应该在nginit中初始化你的数组。
试试这个
ngOnInit() {
this.container = []//add this
// Get Environment id
this._route.params.subscribe(params => {
this.id = params['id'];
// Get Environment
this.environmentService.getEnvironment(this.id).subscribe( environment => {
this.environment = environment;
console.log(environment);
//this.containerName = this.environment.name;
});
// Get Docker processes
this.dockerService.getProcesses(this.containerName).subscribe(processes => {
this.processes = processes;
});
// Get Docker Container Object
this.dockerService.getContainer(this.containerName).subscribe( container => {
this.container = container;
});
// Get Settings
this.settingsService.getSettings().subscribe( settings => {
this.settings = settings;
});
});
}
}