Angulandy2
Angulandy2

Reputation: 806

Angular 2 json getting data objects

I got url which contains data arrays as json. I want to get and use all of the elements in it :

By doing this, i get everything and nothing specific. For example : How to get data.name or data.price.... ?

  ngOnInit() {
    this.http.get('this.url').subscribe(data => {
      console.log(data);

    })

Upvotes: 0

Views: 52

Answers (3)

Gleycer Parra
Gleycer Parra

Reputation: 11

If you are not able of doing data.name for example, then might be that your case is that data has a different structure and does not have the properties directly as children. You should be sure that data has the structure you're mentioning. In some cases there is another data property within, so you can test data.data and see what happens.

Upvotes: -1

Taranjit Kang
Taranjit Kang

Reputation: 2580

  ngOnInit() {
    this.http.get('this.url').subscribe((data:any) => {
      console.log(data.name);

    })

try with any, or you can create a model and replace any with the model (which reflects the data you will recieve)

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222522

You need to use array.find if you want to get the particular object name or price

 this.http.get('this.url').subscribe((data : any) => {
       let price = data.find(t=>t.name ==='yourName').price;
 });

if its just an Object, you could access using the property,

ngOnInit() {
    this.http.get('this.url').subscribe((data:any) => {
      console.log(data.name);
})

Upvotes: 2

Related Questions