订阅后的Angular 2数组具有元素,但长度为0 [英] Angular 2 array after subscribe has elements but length is 0
问题描述
我正在使用Angular 2,并且发现了意外的行为.
I'm using Angular 2 and I have noticed an unexpected behaviour.
我有一个数据源类,该类扩展了DataSource,具有两个变量:
I have a datasource class, which extends DataSource, with two variables:
private archives = new BehaviorSubject<MyArchive[]>([]);
public archives$: Observable<MyArchive[]> = this.archives.asObservable();
private filteredArchive: MyArchive[];
我在课堂上以这种方式更新档案:
I update archives this way within the class:
this.archives.next(this.filteredArchive);
在另一个类的外部,我尝试订阅可观察的对象,但是它不起作用:
Outside in another class I try to subscribe to the observable but it doesn't work:
ngAfterViewInit(): void {
this.dataSource.archives$.subscribe((archive: Array<MyArchive>) => {
console.log(archive.length);
console.log(archive);
console.log(archive.length);
}
}
在控制台日志中它打印:
In the console log it prints:
0
<THE ARCHIVE WITH AN OBJECT INSIDE AS IT SHOULD BE, WITH LENGTH = 1>
0
因为长度为0,所以我无法迭代归档变量.这是怎么回事?
So that I can't iterate on the archive variable because its length is 0. What's going on here?
推荐答案
我解决了这个问题. 我忘记了this.filteredArchive是由HTTP GET请求更新的.我试图使用forEach在this.filteredArchive中推送数据,但是当接收到所有数据时,我忘记了调用then(). 因此,我试图使用订阅访问尚未准备好的结果.
I solved the problem. I forgot that this.filteredArchive is updated by an HTTP GET request. I was trying to push data within this.filteredArchive using forEach, but I forgot to call then() when all the data are received. Hence I was trying to access, using subscribe, a result that was not yet ready.
感谢大家的答复!
这篇关于订阅后的Angular 2数组具有元素,但长度为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!