gpt4 book ai didi

http请求完全加载后的 Angular 动画

转载 作者:太空狗 更新时间:2023-10-29 19:27:59 25 4
gpt4 key购买 nike

我对来自 api 的数据的动画有疑问,例如,如果我想实现一个 Angular 4 交错动画,我需要提供 objects.lenght

<div [@listAnimation]="objects.length">
<div *ngFor="let object of objects">
{{ object?.title }}
</div>
</div>

问题是 objects.lenght 的值在我对 api 的 http 请求完成之前大约不到一秒或更长时间未定义!

这是我的组件

 objects: {};

constructor(private _api: ApiService ) {}

ngOnInit() {
this._api.getAllBlogPosts()
.subscribe(result => this.objects= result);
}

交错动画是这样的

import { trigger, state, animate, transition, style , query , stagger , keyframes} from '@angular/animations';
 
export const listAnimation =

trigger('listAnimation', [
  transition('* => *', [

query(':enter' , style({ opacity: 0 }) , {optional: true}),

query(':enter' , stagger( '300ms' , [
animate('1s ease-in' , keyframes([
style({opacity: 0 , transform: 'translateY(-75px)' , offset: 0}),
style({opacity: .5 , transform: 'translateY(35px)' , offset: 0.3}),
style({opacity: 1 , transform: 'translateY(0)' , offset: 1})
]))
]) , {optional: true}),

query(':leave' , stagger( '300ms' , [
animate('1s ease-in' , keyframes([
style({opacity: 1 , transform: 'translateY(0)' , offset: 0}),
style({opacity: .5 , transform: 'translateY(35px)' , offset: 0.3}),
style({opacity: 0 , transform: 'translateY(-75px)' , offset: 1})
]))
]) , {optional: true})

]),
    ]);

调用完成后有没有办法调用或运行动画?

最佳答案

您可以使用 Angular 的生命周期 Hook ,以便 OnInit 调用服务的方法。在那一刻,你得到了所需的信息。然后运行实现 AfterViewInit 的动画。

检查 https://angular.io/guide/lifecycle-hookshttps://angular.io/api/core/AfterViewInit

更新 1:

可以为一个组件实现多个生命周期钩子(Hook)。假设您的动画有两个状态(来自 https://angular.io/guide/animations 的示例),它看起来像这样:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
...
animations: [
trigger('listAnimation', [
state('inactive', style({
backgroundColor: '#eee',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#cfd8dc',
transform: 'scale(1.1)'
})),
transition('inactive => active', animate('100ms ease-in')),
transition('active => inactive', animate('100ms ease-out'))
])
]
})

export class AppComponent implements OnInit, AfterViewInit {
...
animationState = 'inactive';

constructor(private _api: ApiService ) {}

ngOnInit() {
this._api.getAllBlogPosts()
.subscribe(result => this.objects= result);
}
ngAfterViewInit(){
// run animation by changing the state
this.animationState = this.animationState === 'inactive ' ? 'active' : 'inactive ';
}
}

关于http请求完全加载后的 Angular 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com