Search code examples
javascriptangulartypescriptobservable

How do I extract the year part of an observable ISO Date


I have an angular component class that updates an interface with Object records like this [{"examYear":"2001-01-02T00:00:00.000+00:00"},{...}] received from an Observable GET call to the backend service. The angular Service class has this signature:

export someService{
private dateEndpoint="http://xxx";
constructor(private httpClient:HttpClient){}

fetchDateObj():Observable<SubjectDate[]>{
return this.httpClient.get<SubjectDate[]>(this.dateEndpoint);
}

}

The SubjectDate class is

export class SubjectDate {
examYear: Date;
constructor (examYear: Date){
this.examYear=examYear;
}
}

The component class that calls the fetchDateObj() method of my service component has a method like this

getDates(){
this.someService.fetchDateObj().subscribe(dateObjArr=>{
this.subjectDates=dateObjArr;

//Map record to examYear then extract only unique dates
this.dateArr=(this.subjectDates.map(x=>x.examYear)).filter(this.isUnique);

//log the year of each unique date
this.dateArr.forEach(x=>x.getFullYear());
}

the callback function is like this

isUnique(curr:Date,index: number,arr:Date[]):boolean{
return (index === arr.indexOf(curr))
} 

Though the interface is correctly updated with Date record like Jan 2,2002 after parsing with angular date pipe, but I expected to have a log of something like 2001 etc as the full year, but instead I keep getting this browser console error ERROR TypeError: x.getFullYear is not a function at z.component.ts at Array.forEach(<anonymous>)...


Solution

  • The only thing I did was to create a new Date with the returned ISO date string and it worked as expected.

    this.dateArr=(this.subjectDates.map(x=>x.examYear)).filter(this.isUnique).map(isoString=>new Date(isoString))