I received response object from http service in angular 2 and if i try to console response.prop, it is not working and it is showing following error:
D:/ABC/angular-training/angular_cli/src/app/shared/footer/footer.component.ts (16,28): Property ‘prop’ does not exist on type ‘{}’.)
But when I do response[“prop”] then I get my value.
Here is my code:
export class FooterComponent {
constructor(private httpService : HttpService) {
this.httpService.getData("http://127.0.0.1:8887/footer.json").then(response => {
console.log(response);//shows object
console.log(response.prop);//not works
console.log(response["prop"]);//works fine
});
}
}
here is my Httpservice code:
export class HttpService {
private Title = URL;// URL to web api
constructor(private http: Http) { }
getData(url="this.Title"): Promise<{}> {
return this.http.get(url)
.toPromise()
.then(response =>
response.json()
)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Also this is JSON response from server:
{
"footerLinks" : {
"social":[{
"text":"Google",
"link":"www.google.com"
},
{
"text":"Facebook",
"link":"www.facebook.com"
},
{
"text":"Twitter",
"link":"www.Twiiter.com"
},
{
"text":"Pinterest",
"link":"www.Pinterest.com"
},
{
"text":"LinkedIn",
"link":"www.linkedin.com"
}]
}
}
3
Answers
you need to declare the type of
response
.Try below,
This way Typescript compiler will know what is the type of your response object.
Hope this helps!!
your response probably looks like json but is actually a string.
check the type with
try also ..
or
You may need to add the JSON response header on the server response.
As mentioned, your response is an Object (inside an Object), that is why you need to access the data with
console.log(response["prop"]);
as that is how we access nested objects.Not knowing exactly what you want to extract from your response, if you want the array only, do this:
Service:
If you want to preserve the Object
social
, which contains the array just leave['social']
out from the above code. But I assume you only want the array, as the objectsocial
actually does not contain anything else than the array.Component:
and you can iterate the array:
Notice that I used the safe navigation operator, that prevents app throwing error in case of null values.