我的 firebase项目中有以下设置:
- Clients
- Client 1
- Name
- Services
- Service 1
- Service 2
- Client 2
- Name
- Services
- Service 1
- Service 2
- Service 3
除此之外,我还有一个服务,它为我的组件提供客户端,这是我的组件,它实现了服务:
@Component({
selector: 'app-client-list',
templateUrl: './client-list.component.html',
styleUrls: ['../../dashboard.component.css'],
providers: [clientService]
})
export class ClientListComponent implements OnInit {
clients: Client[];
dataAvailable: boolean;
constructor(private clientService: clientService) {
this.dataAvailable = false;
this.clientService = clientService;
}
ngOnInit() {
this.clientService.getClients().subscribe(res => {
this.clients = res;
this.dataAvailable = true;
});
}
updateSearch(a: string) {
this.cientService.getClient(a);
}
}
这就是我在 HTML 中展示它(或我应该如何)的方式:
<div *ngIf="dataAvailable">
<div id="row" *ngFor="let item of homies">
<span>{{item.name}}</span>
<span>{{item.upcomingServices.length}}</span>
</div>
</div>
现在{{item.upcomingServices.length}}没有显示任何内容,只留下一个空白区域,我已经尝试过这两个版本,但似乎没有任何效果:
{{(item.upcomingServices | async).length}} {{(item.upcomingServices | async)?. length}}
第一个出现此错误:
Cannot read property 'length' of null
第二个给出了这个:
InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
这是我用来检索客户端的服务:
@Injectable()
export class ClientService {
homies: FirebaseListObservable<Client[]>;
subject: BehaviorSubject<any>;
constructor(db: AngularFireDatabase) {
this.subject = new BehaviorSubject('');
this.clients = db.list('/clients', {
query: {
orderByChild: 'name',
startAt: this.subject
}
});
}
getClients() {
this.subject.next('');
return this.clients;
}
getClient(id: number | string) {
this.subject.next(id);
return this.clients;
}
}
如何了解HTML中嵌套数组的长度,在这种情况下显示客户端时的服务长度。
答案 0 :(得分:1)
您应该在显示模板之前订阅该功能并添加条件,如下所示。 声明一个布尔变量,如下面的
dataAvailable:boolean=false;
并像这样修改ngOnInit方法
this.clientService.getClients().subscribe(res=>{
this.clients=res;//res.json() if it is not json already
this.dataAvailable=true;
});
并修改您的模板,如下所示
<div *ngIf="dataAvailable">
<div id="row" *ngFor="let item of clients " >
<span>{{item.name}}</span>
<span>{{item.upcomingServices.length}}</span>
</div>
</div>