【发布时间】:2018-08-03 22:33:57
【问题描述】:
我正在使用“angular2-virtual-scroll”来实现按需加载。这些项目过去是由 observable 使用父组件触发的异步管道驱动的。现在我正试图从孩子那里打电话给我的服务。调用成功,我得到了我的数据,我需要使用订阅事件来应用其他逻辑。问题是当我在订阅函数中更新我的数组时,检测到的更改似乎不起作用。我读过其他类似的问题,但我没有找到解决方案。
这是使用服务调用的主要组件。初始请求是从 onInit 完成的。然后当你向下滚动时调用 fetchMore。
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { User } from './../models/user';
import { Role } from './../../roles/models/role';
import { UsersService } from './../services/users.service';
import { ChangeEvent } from 'angular2-virtual-scroll';
import { promise } from 'selenium-webdriver';
import { VirtualScrollComponent } from 'angular2-virtual-scroll';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-users-list',
template: `
<div class="status">
Showing <span class="">{{indices?.start + 1}}</span>
- <span class="">{{indices?.end}}</span>
of <span class="">{{users?.length}}</span>
<span>({{scrollItems?.length}} nodes)</span>
</div>
<virtual-scroll [childHeight]="75" [items]="users" (update)="scrollItems = $event" (end)="fetchMore($event)">
<div #container>
<app-user-info *ngFor="let user of scrollItems" [roles]="roles" [user]="user">
<li>
<a [routerLink]="['/users/edit/', user.id]" class="btn btn-action btn-edit">Edit</a>
</li>
</app-user-info>
<div *ngIf="loading" class="loader">Loading...</div>
</div>
</virtual-scroll>
`
})
export class UsersListComponent implements OnInit, OnDestroy {
users: User[] = [];
@Input() roles: Role[];
currentPage: number;
scrollItems: User[];
indices: ChangeEvent;
readonly bufferSize: number = 20;
loading: boolean;
userServiceSub: Subscription;
constructor(private usersService: UsersService) {
}
ngOnInit() {
this.reset();
}
ngOnDestroy() {
if(this.userServiceSub) {
this.userServiceSub.unsubscribe();
}
}
reset() {
this.loading=true;
this.currentPage = 1;
this.userServiceSub = this.usersService.getUsers(this.currentPage).subscribe(users => {
this.users = users;
});
}
fetchMore(event: ChangeEvent) {
if (event.end !== this.users.length) return;
this.loading=true;
this.currentPage += 1;
this.userServiceSub = this.usersService.getUsers(this.currentPage).subscribe(users => {
this.users = this.users.concat(users);
});
}
}
根据我的阅读,这可能是一个上下文问题,但我不确定。任何建议都会很棒。
“编辑”
查看插件组件的源代码,我可以看到更改事件的捕获位置。
VirtualScrollComponent.prototype.ngOnChanges = function (changes) {
this.previousStart = undefined;
this.previousEnd = undefined;
var items = changes.items || {};
if (changes.items != undefined && items.previousValue == undefined || (items.previousValue != undefined && items.previousValue.length === 0)) {
this.startupLoop = true;
}
this.refresh();
};
如果我在此事件中设置断点,它会在初始加载时触发,因此当我们将数组实例化为 [] 时。当我点击页面时它会触发。但是当数组在订阅事件中更新时它不会触发。我什至在其中放了一个按钮,将数组设置为空,并更新视图,因此订阅函数一定会破坏更改检测。
【问题讨论】:
标签: javascript angular observable angular2-observables angular2-changedetection