Search code examples
angularangular2-servicesangular6

How to pass today date to 'new BehaviorSubject(date)' Angular 6


I have a angular 6 use case in which, I need to update date in app component, which will be used by all the other components, which will be hitting mysql DB to fetch the data using select query with the above date. Which I was able to achieve, by writing a service.

Now I want the default date to be present as today or the erday, returned from

SELECT valval FROM global_configs WHERE valname = 'erday'

for which service was written as below

@Injectable()
export class ErdayService {

  public baseUrl = 'http://localhost:8080/api';
  public erday:any;  
  **private dateSource = new BehaviorSubject('Default Date');**
  currentMessage = this.dateSource.asObservable();

  constructor(private _http: Http) { }

  getErday() {

    return this._http.get(this.baseUrl + '/erday');
    }

    changeMessage(message: string) {
      console.log("getting message...",message);
      this.dateSource.next(message)
    }

    setDate(dateValue:any){
      this.dateSource.next(dateValue);  
    }
}

but I want to pass today's date or 'erday' received from getErday() instead of 'Default Date' in private dateSource = new BehaviorSubject('Default Date');

Can someone please help me. I'm new to Angular and services & Observables are always confusing for me.


Solution

  • if you want to pass today's date use javascript's Date:

    private dateSource = new BehaviorSubject<any>(new Date().toLocaleDateString()));
    

    if you want to pass 'erday' received from getErday() you can use tap operator to tap into flow of observable

    import {tap} from 'rxjs/operators';//
    private dateSource = new BehaviorSubject<any>('Default Date');
            return this._http.get(this.baseUrl + '/erday').
            pipe(tap(result=>
            {this.setDate(result);
            return result;})
            );