-1

Is there a way in which I can update say the time of a Subject within my service?

I am thinking of abstracting the following function into a service:

date: Date;

setTime(hours: number, mins: number, secs: number): void {
    this.date.setHours(hours);
    this.date.setMinutes(mins);
    this.date.setSeconds(secs);
  }

service example

date: Subject<Date>;

  constructor() {
    this.date = new Subject();
  }

  setDate(hrs: number, mins: number, secs: number): Observable<Date> {
    const tempDate = this.date;
    // tempDate.set - Cannot do .setXXX here since it is a Subject and not a Date
    this.date.next
  }

stackblitz

physicsboy
  • 5,656
  • 17
  • 70
  • 119

1 Answers1

1

You could just create a new date, that copies the date part of the current date, and uses time parameters. and then push the tempDate to the subject.

something like this:

setDate(hrs: number, mins: number, secs: number): Observable<Date> {
   let tempDate = this.date.getValue(); //gets the value of the subject, not the actual subject
   tempDate.setHours(hours);
   tempDate.setMinutes(mins);
   tempDate.setSeconds(secs);
   this.date.next(tempDate);
}
Teun van der Wijst
  • 939
  • 1
  • 7
  • 21
  • `'getValue' does not exist on type 'Subject` :-( – physicsboy Oct 05 '18 at 14:33
  • is it possible to change `Subject` to `BehaviourSubject` ? explanation: https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject – Teun van der Wijst Oct 05 '18 at 14:57
  • Hmm. It accepts the BehaviorSubject definition, but I still cann't get to the `.setXXX` functions. I have saved as a new stackblitz: https://stackblitz.com/edit/off-time-edit-behaviorsubject – physicsboy Oct 06 '18 at 09:55
  • @physicsboy I've updated your stackblitz. It's working now, the problem is you dit `const tempDate = this.date` and you should've done `const tempDate = this.date.getValue()` once i did that i was abe to access `.setXXX` functions. have a look – Teun van der Wijst Oct 08 '18 at 06:38