使用 setTimeout() 的自定义 Angular 通知消息显示问题

Custom Angular notification message display problem using setTimeout()

我在屏幕上显示通知消息时遇到问题。 当我单击按钮以显示通知消息时,弹出窗口会在间隔中定义的几秒后显示并删除。但是当我多次点击按钮时,弹出窗口不会保持可见状态,比如 2 秒,但只有 1 秒或更短时间,有时它只会在屏幕上闪烁。

我希望它的行为方式是,当我单击该按钮时,所有以前的弹出窗口都将被删除并显示新的弹出窗口,该窗口将显示 2 秒(除非下一次单击按钮和新弹出窗口显示)或者旧弹出窗口将显示 2 秒,新弹出窗口将放置在前一个 one/s.

上方

您有什么更正的建议吗:

这是我的代码: HTML:

<div class="container">
  <div class="notifications">
    <scale-notification-message 
      variant="success" 
      opened
      @fadeAnimation
      *ngIf="successMessage$ | async as successMessage">
      {{ successMessage }}
    </scale-notification-message>
  </div>

  <button 
    type="button" 
    class="btn" 
    (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('');
  }
}

它不起作用,因为在明文消息中您正在再次设置消息,这将在 2 秒后触发新的超时。

对于这种情况,您可以通过将代码更改为以下内容来避免这种情况:

  successMessage$: Observable<string> = this.notificationService.successMessageAction$.pipe(tap(value => {
  if(!!value){
    setTimeout(() => {
      this.notificationService.clearSuccessMessage();
    }, 2000);
  }

})
);

Thank you very much for your correction. I corrected the code but I >still have the issue that when I click on the button again while the >previous popup is visible and then click again when the popup disappears, the popup stays visible for just a second or it just flashes on the screen. – Victoria 3 hours ago

为此你可以使用:

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);
  }
  })
);