Reputation: 85
i am making a get request to an api endpoint, which sends a json object ,i want courses array from data property.but i am not able to, do not know what am oi doing wrong ,should in convert json to object .... the error is Property 'key' does not exist on type 'Object'.
here key should be equal to "data" and data is property of the json.
my component is
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators'
import { C } from './c.model';
@Component({
selector: 'app-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
courses :C[]=[];
constructor(private http:HttpClient) { }
ngOnInit(): void {
this.fetchCourses();
}
private fetchCourses() {
this.http.get('http://127.0.0.1:3000/api/courses/')
.pipe(map( responseData =>{
const coursesArray = [];
for(const key in responseData){
if(responseData.hasOwnProperty(key)){
if(key === "data")
{
coursesArray.push(...(responseData.key.courses))
}
}
}
return coursesArray
}))
.subscribe(responsec=>{
this.courses=responsec;
})
}
}
json from api
{
"status": "sucess",
"numberOFResults": 5,
"data": {
"courses": [
{
"images": [],
"tutors": [],
"_id": "611c8899e135aa2c9cd39796",
},
{
"images": [],
"tutors": [],
"_id": "611c8899e135aa2c9cd39794",
"name": "arduno uno",
},
{
"images": [],
"tutors": [],
"_id": "611c8899e135aa2c9cd39795",
"name": "c/c++",
"duration": 8,
},
{
"images": [],
"tutors": [],
"_id": "611c8899e135aa2c9cd39798",
"name": "ms office",
"duration": 4,
},
{
"images": [],
"tutors": [],
"_id": "611c8899e135aa2c9cd39797",
"name": "web development",
}
]
}
}
Upvotes: 0
Views: 1801
Reputation: 3727
key
here is of type string and you are accessing the property using . (dot). You need to access it using the bracket [] syntax.
Change this
coursesArray.push(...(responseData.key.courses))
to
coursesArray.push(...((responseData as any)[key].courses))
Upvotes: 1