0

I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve. I was able to get JSON's data before but now that it's nested I don't know how to get it's data. This is what I've done so far

Service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class TestService {
    url = "http://localhost:80/assets/data/test.json";
    constructor(private http:Http) { }

    getTestWithObservable(): Observable<any> {
        return this.http.get(this.url)
            .map(this.extractData)
            .catch(this.handleErrorObservable);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body;
    }

    private handleErrorObservable (error: Response | any) {
        console.error(error.message || error);
        return Observable.throw(error.message || error);
    }
}

Component

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { TestService } from './test.service';

@Component({
    selector: 'ngx-test',
    styleUrls: ['./test.component.scss'],
    templateUrl: './test.component.html',
})

export class TestComponent implements OnInit {
    observableTest: Observable<any>
    errorMessage: String;

    constructor(private testService: TestService) { }

    ngOnInit(): void {
        this.testService.getTestWithObservable().subscribe(
            res => {
                let user = res[0]["users"];
                let user_data = user["data"];
                console.log(user_data["name"]);
            }
        );
    }
}

JSON

[{
    "id": 1,
    "users": {
        "user_id": 14,
        "data": [{
            "name": "James",
            "age": 20
        },
        {
            "name": "Damien",
            "age": 25
        }]
    }
}]

HTML

<div *ngFor="let x of user_data; let i = index">
    {{x.name}}
</div>

I'd appreciate if someone can point me out the solution or what I'm doing wrong.

3
  • are you getting data when console.log? Commented Jul 5, 2018 at 20:31
  • user_data is an array, so you need user_data[0]["name"] (although there is no reason the use square bracket syntax for the property, may as well do user_data[0].name) Commented Jul 5, 2018 at 20:31
  • this.user_data=res[0].users.data. Explain: res is an Array, res[0] is an object that have users property. users property has a property data that is the array you're looking for Commented Jul 5, 2018 at 20:33

2 Answers 2

2

You need to save the data in an instance property to access it. user_data is local to your function, you cannot access it in the template so you should use something like this :

export class TestComponent implements OnInit {
    observableTest: Observable<any>
    errorMessage: String;
    user_data: any;

    constructor(private testService: TestService) { }

    ngOnInit(): void {
        this.testService.getTestWithObservable().subscribe(
            res => {
                let user = res[0]['users'];
                let user_data = user['data'];
                console.log(user_data['name']);
                this.user_data = user_data; // here
            }
        );
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Every double quotation should be change into single quote marks as "users" -> 'users'
0

There is some problems with your code:

export class TestComponent implements OnInit {
  observableTest: Observable<any>
  errorMessage: String;

  user_data: any;

  constructor(private testService: TestService) {
  }

  ngOnInit(): void {
    this.testService.getTestWithObservable().subscribe(
      res => {
        let user = res[0]["users"];
        this.user_data = user["data"];
        console.log(user_data["name"]);
      }
    );
  }
}

In Angular >= 4, pipe methods is better to handle Observable

this.http.get(this.url)
  .pipe(
    filter(...),
    map(...)
  )

With HttpClient (Http is deprecated), the .json() is done for you. You don't need your extractData function.

  • You have to initialize your variable. And use "this" to refer to it.

2 Comments

The OP's code isn't using HttpClient, so extractData is needed. That said, the code should almost definitely be updated to use HttpClient
Thanks for the tip, I've already choose the correct answer but yeah, that was the problem. Many thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.