I am currently retrieving json data from a file with various fields - i am interested in 2 fields and each of the 2 field i would like to have them set to different arrays.
SERVICE file:
getCourseType(){
return this._http.get('url')
.map((res:Response) => <ICourseType[]> res.json())
.do(data =>console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
COMPONENTS.ts file:
courseType: ICourseType[];
courseName: any[] = [];
courseRoster: any[] = [];
getCourseType(){ //function called from ngOnInit()
this.dataService.getCourseType().subscribe(
data => this.courseType = data,
error => this.errorMessage = <any>error);
}
JSON file:
[
{
"id": 1,
"courseTitle": "English",
"courseNumber": 340B,
"roster": 23,
},
{
"id": 2,
"courseTitle": "AP History",
"courseNumber": 1420,
"roster": 14
},
{
"id": 3,
"courseTitle": "Art",
"courseNumber": 42A,
"roster": 30
}
]
Currently i am return the json object but if i am interested in gathering all the courseTitle of each of the courses into one array and then all the roster number of each of the courses into one array - where should i do that? In the service or in my components?
In your component file
courseType: ICourseType[];
courseName: any[];
courseRoster: any[];
getCourseType(){ //function called from ngOnInit()
this.dataService.getCourseType().subscribe(
data => {
this.courseType = data
this.courseType.forEach(course=>{
this.courseName.push(course.courseTitle);
this.courseRoster.push(course.roster);
})
},
error => this.errorMessage = <any>error);
}