我在螢屏上顯示通知訊息時遇到問題。當我單擊按鈕以顯示通知訊息時,會在間隔中定義的幾秒鐘后顯示并洗掉彈出視窗。但是,當我多次單擊按鈕時,彈出視窗不會保持可見狀態,比如說 2 秒,但只有 1 秒或更短時間,有時它只會在螢屏上閃爍。
我希望它的行為方式是這樣的,當我單擊按鈕時,任何以前的彈出視窗都將被洗掉并顯示新的彈出視窗,該彈出視窗將顯示 2 秒鐘(除非下次單擊按鈕和新彈出視窗顯示)或者舊的彈出視窗將顯示 2 秒,新的彈出視窗將放置在前一個/秒的上方。
您對更正有什么建議:
這是我的代碼:HTML:
<div >
<div >
<scale-notification-message
variant="success"
opened
@fadeAnimation
*ngIf="successMessage$ | async as successMessage">
{{ successMessage }}
</scale-notification-message>
</div>
<button
type="button"
(click)="onClick()">
Click
</button>
</div>
TS檔案
import { tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'notification-messages';
visible: boolean = true;
successMessage$: Observable<string> = this.notificationService.successMessageAction$.pipe(tap(_ => {
setTimeout(() => {
this.notificationService.clearSuccessMessage();
}, 2000)
})
);
constructor(private notificationService: NotificationService) {}
onClick() {
this.notificationService.setSuccessMessage('Button clicked!');
}
}
服務
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private successMessageSubject = new Subject<string>();
successMessageAction$ = this.successMessageSubject.asObservable();
setSuccessMessage(message: string) {
this.successMessageSubject.next(message);
}
clearSuccessMessage() {
this.setSuccessMessage('');
}
}
uj5u.com熱心網友回復:
它不起作用,因為在清除訊息中您再次設定訊息,這將在 2 秒后觸發新的超時。
對于這種情況,您可以通過將代碼更改為以下內容來避免這種情況:
successMessage$: Observable<string> = this.notificationService.successMessageAction$.pipe(tap(value => {
if(!!value){
setTimeout(() => {
this.notificationService.clearSuccessMessage();
}, 2000);
}
})
);
非常感謝您的指正。我更正了代碼,但我>仍然有一個問題,當我再次單擊按鈕時,>上一個彈出視窗可見,然后在彈出視窗消失時再次單擊,彈出視窗只保持一秒鐘可見,或者它只是在螢屏上閃爍. – 維多利亞 3 小時前
為此,您可以使用:
timeout: any = null;
successMessage$: Observable<string> =
this.notificationService.successMessageAction$.pipe(tap(value => {
if(!!this.timeout){
clearTimeout(this.timeout);
}
if (!!value) {
this.timeout = setTimeout(() => {
this.notificationService.clearSuccessMessage();
this.timeout = null;
}, 2000);
}
})
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365776.html
上一篇:角度資料源過濾器
