【发布时间】:2019-04-23 11:34:35
【问题描述】:
所以我想根据列表中的项目数是否大于 3 来显示一个图标。我正在使用这个 getProjects() 函数,我需要订阅它才能获取数据。我在订阅时设置了一个布尔值来检查列表中的项目数量,然后在我的 HTML 中,我使用 ngIf 来显示基于布尔值的图标。我能够让它正确显示,但是,我想我会不断地在我的订阅中轮询,并一遍又一遍地设置这个布尔值,因为它让我的网页运行得非常慢。
我已经尝试过 take(1) 方法,该方法似乎不会停止订阅,并将其设置为组件内的“this.variable”范围。我目前正在使用事件发射器,但这也不起作用。
这是我目前的代码,
我订阅的函数(在不同的组件中):
getProjects(): Observable<ProjectInterfaceWithId[]> {
const organizationId = localStorage.getItem('organizationId');
return this.firestoreService.collection('organizations').doc(organizationId)
.collection('projects').snapshotChanges()
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as ProjectInterface;
const id = a.payload.doc.id;
return {id, ...data} as ProjectInterfaceWithId;
})),
map(list => {
if (list.length !== 0) {
this.buildProjectLookup(list);
this.projects = list;
return list;
}
})
);
}
我用来获取数据和设置布尔值的函数:
@Input() toggle: boolean;
@Output() iconStatus = new EventEmitter();
displayIcon() {
this.projectService.getProjects()
.pipe(take(1))
.subscribe(
list => {
if(list.length >= 3){
this.toggle = true;
this.iconStatus.emit(this.toggle);
}
});
}
HTML:
<i *ngIf="displayIcon()" class="material-icons">list</i>
有没有什么办法让我只检查一次列表长度,这样我就不会陷入这个订阅循环?提前谢谢!
【问题讨论】:
标签: html angular event-handling parent-child infinite-loop