Modify Child object With data from Parent Object

mail@pastecode.io avatar
unknown
typescript
5 months ago
2.6 kB
10
Indexable
Never
// Base Task Model
export class Task {
  constructor(
      public goal_id: string,
      public name: string,
      public description: string,
      public priority: string,
      public taskDate: string,
  ) {}
}


// Base Goal Model
export class Goal {
  constructor(
      public name: string,
      public isMainGoal: boolean,
      public details: string,
      public category: string,
      public lifeArea: string,
      public creationDate: string,
      public priority: string,
      public endDate: Date,

  ) {}
}



// Task Service

  tasksCollection():Observable<any> {
    return this.fetchTasks()
      .pipe(
        map(response => {
          const tasksArray = [];
          for (const key in response) {
            if (response.hasOwnProperty(key)) {
              tasksArray.push({ ...response[key], id: key });
            }
          }
          return tasksArray;
        })
      );
  }

// Goal Service

getGoalById(id:string):Observable<any> {
    return this.goalsCollection()
    .pipe(
      map(response => {
        response = response.filter((v:any) => v.id === id);
        return response;
      })
    )
}


// How, in Dashboard Component, modify each Task Item from tasksCollection so that new Key(goalCategory) and Value
// being the category name from queried Goal Object (queried Goal based on foreign key) is added to each Task ?




// Dashboard Component
export class DashboardComponent implements OnInit {

    goalCategory!:any; // parameter to which new value is supposed to be assigned with the help of getGoalCategory method on each iteration inside tasksArray
    
    ngOnInit() {
        this.tasksService.tasksCollection()
        .pipe(
            concatMap(tasksArray => {
    
              tasksArray = tasksArray.map((item:any) => {
                this.getGoalCategory(item); // method which 
                return {
                  goal_id: item.goal_id,
                  description: item.description,
                  id: item.id,
                  isMainGoal: item.isMainGoal,
                  name: item.name,
                  goalCategory: this.goalCategory // -> new key with value from Goal!
                }
              })
              return tasksArray;
            })
        )
        .subscribe(
            (tasks:any) => {
              console.log(tasks);
            }
          )
    }
    
    // Helper Method
    getGoalCategory(item:any) {
    		this.goalsService.getGoalById(item.goal_id).subscribe(d => {
          this.goalCategory = d;
        })
    }

}