我正在使用 Angular 开发 Electron 应用程序,主页应该显示从 JSON 文件异步加载的项目列表。
它们加载和动画效果很好,但为了错开它们的动画,我调用了 angular animate 的 Query 函数。
不幸的是,此查询返回零个元素,尽管事实上它们几乎立即成功加载,并带有正确的动画(只是没有交错)。
我怀疑这与加载数据之前触发的查询有关,但我不确定我能做些什么来解决这个问题。
相关代码如下。
HTML:
<div [@itemList]="itemService.items.length">
<div class="item-card" *ngFor="let item of itemService.items |
async;">
</div>
</div>
组件:
@Component({
selector: 'app-notes-list',
templateUrl: './notes-list.component.html',
styleUrls: ['./notes-list.component.css'],
animations: [
trigger('items', [
transition(':enter', [
style({ transform: 'scale(0.5)', opacity: 0 }), // initial
animate('1s cubic-bezier(.8, -0.6, 0.2, 1.5)',
style({ transform: 'scale(1)', opacity: 1 })) // final
]),
transition(':leave', [
style({ transform: 'scale(1)', opacity: 1, height: '*' }),
animate('1s cubic-bezier(.8, -0.6, 0.2, 1.5)',
style({
transform: 'scale(0.5)', opacity: 0,
height: '0px', margin: '0px'
}))
])
]),
trigger('itemList', [
transition(':enter', [
query('.item-card', stagger(3000, animateChild()))
]),
])
]
})
export class NotesListComponent implements OnInit {
constructor(private itemService: ItemService) { }
ngOnInit() {
this.getItems();
}
getItems(): void {
this.itemService.getItems();
}
}
服务:
@Injectable()
export class ItemService {
items: Subject<Item[]>;
itemDataStore: Item[];
constructor(private electronService: ElectronService,
private zone: NgZone) {
this.items = new Subject<Item[]>();
this.electronService.ipcRenderer.on('sending-items', (event, args) => {
this.itemDataStore = args;
this.zone.run(() => {
console.log('Got data');
this.items.next(this.itemDataStore);
});
});
};
getItems(): Observable<Item[]> {
this.electronService.ipcRenderer.send('get-items');
return this.items.asObservable();
}
}
最佳答案
items: Subject<Item[]>;
应该在调用服务的组件中。
然后您应该订阅返回 Observable 的方法,以获取组件中的项目。它应该看起来接近于此:
this.itemService.getItems().subscribe(data => {
this.items = data;
});
然后在component.html
<div [@itemList]="items.length">
<div class="item-card" *ngFor="let item of items |
async;">
</div>
</div>
更新
要解决问题(未定义的长度),请在查询中将可选参数设置为 true :
trigger('itemList', [
transition(':enter', [
query('.item-card', [
stagger(3000, [
animateChild()
]),
], { optional: true })
]),
])
在 div 中:[@itemList]="items?.length"
关于javascript - Angular 动画查询错误地返回零元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929363/