Reputation: 1092
I have a message service that emits a message whenever the API method is called. The idea is so that all other components in my app can call methods from the service to display either error or success messages.
import { Injectable } from '@angular/core';
import { MessagingComponent } from ',/messaging.component';
import { ReplaySubject } from 'rxjs';
@Injectable()
export class MessageService {
public messages$: ReplaySubject<Object> = new ReplaySubject<Object>(1);
constructor() {
this.messages$.next({
message: '',
type: null
});
}
showError(message: string, time: number): void {
this.messages$.next({
message,
type: 'message-error',
time: time
});
hideMessage(){
this.messages$.next({
message: '',
type: null
});
}
The idea is that any other component can call messageService.showError('my error message', 3000)
. I'm confused as to how to get my showError
method to call the hideMessage
method after 3 seconds, or however long the caller provided for time
.
Upvotes: 1
Views: 1158
Reputation: 28592
showError(message: string, time: number): void {
this.messages$.next({
message,
type: 'message-error',
time: time
});
setTimeout(this.hideMessage,time);
}
Or , the Rxjs way , which is ridiculously complicated :
1- You need to create a delay property inside your service :
export class YouService{
private delay = 3000; // default delay;
...
2- You need to create a delayed version of message$ like this :
this.delayableMessage$ =
this.message$.asObservable().flatMap( ( message ) => {
return Observable.of( message ).delay( this.delay )
} );
3- Every hideMessage and showError could update the delay ;
showError(message: string, time: number): void {
this.delay = 0;
this.messages$.next({
message,
type: 'message-error',
time: time
});
this.hideMessage(time);
}
hideMessage(time){
this.delay = time;
this.messages$.next({
message: '',
type: null
});
}
4- You need to tell your subscribers to subscribe to this.$delayableMessage
;
Basically , create an observable , subscribe to it with delay and the with flatMap map it to a new observable and return that for subscribers.
Upvotes: 2