1

I am new to Angular10 and I am trying to loop through a JSON object but can't work it out.

My JSON object:

[
{
ID: "2",
testata: "Corriere.it - Homepage",
url: "http://xml2.corriereobjects.it/rss/homepage.xml",
categoria: "QUOTIDIANI"
},
{
ID: "3",
testata: "Open",
url: "https://www.open.online/feed/",
categoria: "NEWS"
},
{
ID: "4",
testata: "ANSA.it",
url: "https://www.ansa.it/sito/ansait_rss.xml",
categoria: "NEWS"
}
]

Part of my Angular script:

this.httpClient.get('http://localhost/myjson.json').subscribe(data => {                     
                datax.forEach(element => {              
                console.log(element.url);
            });
    

The error

error TS2339: Property 'forEach' does not exist on type 'Object'.
datay.forEach(element => {
3
  • Have you tried to log what's inside data after you subscribe? I think it might be an object with response property. Commented Oct 29, 2020 at 10:47
  • Another question is if you're able to get this .json file if you enter that URL in browser? Commented Oct 29, 2020 at 10:48
  • thanks Michal, for now i solved the error by defining "any" the array Commented Oct 29, 2020 at 12:21

2 Answers 2

2

Kindly change your code as below as a temporary fix.

this.httpClient.get('http://localhost/myjson.json').subscribe((data: any)=> {                     
            data.forEach(element => {              
            console.log(element.url);
        });
});

Typescript expects a type for response by default. If not provided, it assumes as object.

On the side note, it is not recommended to type a value as any. Kindly use proper typing for the value.

Sign up to request clarification or add additional context in comments.

Comments

1

i think your problem is whan you declare the response you call it 'data' but when you try to use it you call it 'datax'

3 Comments

sorry, you're right, but i just badly copied the code here, the array is always "data"
so the problem remains? if it does try this: instead of writing data => {} write (data: any) => {}
In fact I did as adhs91 said (and you too oded) and I solved it, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.