Modify Child object With data from Parent ObjectV3
unknown
typescript
2 years ago
2.7 kB
43
Indexable
// 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() { // Fetch Tasks this.tasksService.tasksCollection() .pipe( map(tasksArray => { tasksArray = tasksArray.map((item:any) => { this.getGoalCategory(item); // method which is supposed to assign new value to this.goalCategory parameter return { ...item, goalCategory: this.goalCategory // -> new key with value from Goal! } }) return tasksArray; }) ) // do każdego elementu tablicy dodaj nowy obiekt z kategorią rodzica .subscribe( tasks => { console.log(tasks); } ) } // Helper Method getGoalCategory(item:any) { this.goalsService.getGoalById(item.goal_id).subscribe(d => { this.goalCategory = d[0].category; // IMPORTANT! // this.goalCategory is accessible here, it works here, however 'this.goalCategory' returns 'undefined' // in the code above inside ngOnInit in Dashboard // Component }) } }
Editor is loading...