我想在应用程序通知中显示一些消息。 它应该是这样的:
我想要的是,当我单击按钮时,通知动画仍在运行,以完全停止该动画并立即显示新动画,如下所示:
我之前在另一个项目中做过此操作,但相同的方法在这个项目中不起作用,因为我收到此错误:
注意:此消息组件在另一个组件上调用
TS:
import { Component, OnInit } from '@angular/core';
import { ValidatorsService } from '../../../services/validators.service';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: ['./message.component.scss'],
})
export class MessageComponent implements OnInit {
startAnimationTimeout: NodeJS.Timeout | undefined;
endAnimationTimeout: NodeJS.Timeout | undefined;
constructor(public validatorsService: ValidatorsService) { }
ngOnInit() {
let card = document.querySelector('.message-card') as HTMLDivElement;
let timeBar = document.querySelector('.time-bar') as HTMLDivElement;
this.showMessage(card, timeBar);
}
messageAnimation(card: HTMLDivElement, timeBar: HTMLDivElement) {
if (this.validatorsService.messageIndex <= this.validatorsService.messages.length - 1) {
timeBar.classList.remove('slideToLeft')
}
clearTimeout(this.startAnimationTimeout);
this.startAnimationTimeout = setTimeout(() => {
timeBar.classList.add('slideToLeft');
this.endAnimationTimeout = setTimeout(() => {
if (this.validatorsService.messageIndex >= this.validatorsService.messages.length - 1) {
card.classList.replace('slideDown', 'slideUp');
setTimeout(() => {
card.classList.replace('slideUp', 'hide');
timeBar.classList.remove('slideToLeft')
}, 750);
}
}, 2000);
}, 500);
}
showMessage(card: HTMLDivElement, timeBar: HTMLDivElement) {
if (this.validatorsService.messages.length === 1) {
clearTimeout(this.startAnimationTimeout);
clearTimeout(this.endAnimationTimeout);
this.messageAnimation(card, timeBar);
return;
}
if (this.validatorsService.messageIndex >= this.validatorsService.messages.length) {
clearTimeout(this.startAnimationTimeout);
return;
}
this.messageAnimation(card, timeBar);
setTimeout(() => {
this.validatorsService.messageIndex++;
this.messageAnimation(card, timeBar);
this.showMessage(card, timeBar);
}, 2600);
return;
};
}
HTML:
<div #card class="message-card slideDown">
<p class="message"
[ngClass]="{'validMessage': validatorsService.messageType === 'success', 'warningMessage': validatorsService.messageType === 'warning'}">
<span *ngIf="validatorsService.messageType === 'error'">Error
{{validatorsService.messageIndex + 1}} of {{validatorsService.messages.length}}:</span>
{{validatorsService.messages[validatorsService.messageIndex]}}</p>
<div #timeBar class="time-bar"
[ngClass]="{'valid': validatorsService.messageType === 'success', 'warning': validatorsService.messageType === 'warning'}">
</div>
</div>
您应该使用 number 作为超时变量的类型,而不是 NodeJS.Timeout。
startAnimationTimeout: number | undefined;
endAnimationTimeout: number | undefined;