Home > Net >  angular return message after setTimeout
angular return message after setTimeout

Time:11-04

I want to make a function that receive error message string then after some time to disappear, I want to call this function along my application so no need to write the whole code every time I have error response , I tried the code below which works fine but I feel it is still big and can be more short please advice

this code in commonService.ts file

clearErrorMsg = () => {
  return new Promise<string>((resolve) => {
    setTimeout(() => {
      resolve('');
    }, 3000);
  });
};

async errorMessageClear(){
  return await this.clearErrorMsg();
};

and here I call it from different ts file

 const mainFunction = async () => {
   this.error = err.message;
    this.error = await this._commonService.clearErrorMsg();
  };
   
  mainFunction();

HTML

          <ngb-alert [type]="'danger'" [dismissible]="false" 
          *ngIf="error">
            <div >
              <p>{{error}}</p>
            </div>

CodePudding user response:

You can write a service to display error message using MatSnackBar: @angular/material/snack-bar like this:

@Injectable({ providedIn: 'root'})
export class ToastrService {
    constructor(private snackbar: MatSnackBar) { }

    success(message: string) {
        this.snackbar.open(message, undefined, { panelClass: 'success', duration: 5000 });
    }

    error(message: string) {
        this.snackbar.open(message, undefined, { panelClass: 'error', duration: 5000 });
    }

    info(message: string) {
        this.snackbar.open(message, undefined, { panelClass: 'info', duration: 5000 });
    }

    warning(message: string) {
        this.snackbar.open(message, undefined, { panelClass: 'warning', duration: 5000 });
    }
}
  • duration: 5000 => message will hide after 5 second. then when you use:
  • declare private toastr: ToastrService in constructor
  • display when error: this.toastr.error(message);

Hope this help!

Edited: Or you want to get message to process, you can use Subject from rxjs and write service like this:

@Injectable({ providedIn: 'root'})
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: any) {
        this.subject.next(message);
    }

    clearMessages() {
        this.subject.next(null);
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

and then use where you want:

  • declare private messageService: MessageService

  • get message like this:

      this.messageService.getMessage().subscribe(response => {
          // your code    
      });
    

CodePudding user response:

You can use rxjs operators instead of defining a custom promise:

async errorMessageClear() {
  lastValueFrom(
    timer(3000).pipe(
      take(1),
      map(() => '')
    )
  )
};

This will basically do the same thing: return a promise, which will resolve after 3 seconds with an empty string. Nevertheless the closing of your alert is a bit odd. Usually in NgbAlert objects you have the .close() function which should be used.

  • Related