角度动画查询错误地返回零元素

问题描述 投票:2回答:1

我正在使用Angular处理Electron应用程序,主页面应该显示从JSON文件异步加载的项目列表。

它们加载和动画很好,但为了交错动画,我调用了角度动画的查询功能。

不幸的是,这个查询返回零元素,尽管他们几乎立即成功加载了正确的动画(只是没有交错)。

我怀疑这与在加载数据之前触发查询有关,但我不知道我能做些什么来解决这个问题。

相关代码包含在下面。

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();
    }
}
javascript angular rxjs electron angular-animations
1个回答
5
投票

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"

© www.soinside.com 2019 - 2024. All rights reserved.