Home > OS >  How to change the value of an Observable of Object Arrays
How to change the value of an Observable of Object Arrays

Time:10-28

how can i change a single property of an Observable of an Object Array. In my service im doing an http request to get all Tasks:

getTasks(): Observable<Task[]> {
  return this.httpClient.get<Task[]>('http://localhost:8080/tasks');
}

This is my Task Interface:

export interface Task {
  id: number;
  name: string;
  dueDate: Date;
  taskstatus: TaskStatus;
  user: User;
}

The Problem is, the dueDate of the Respone Object of the http Request ist just a string, although I defined it in the database as Timestamp, i just get a timestamp as string like "2021-09-25T11:36:29.000 00:00".

Now my question is how can i change the value inside the Observible something like: task.dueDate = new Date(task.dueDate) so that i can transform all date strings into actual Date types. (for all Objects of the Array)

CodePudding user response:

the map operator is used for data transforms on observables, and you'll use the array map inside of the rx map to transform each object in the array:

getTasks(): Observable<Task[]> {
  return this.httpClient.get<Task[]>('http://localhost:8080/tasks').pipe(
    map(tasks => tasks.map(task => {
      // do whatever to the task
      task.dueDate = new Date(task.dueDate);
      return task;
    }))
  );
}

you might need to fiddle with your typings to make it compile though.

  • Related