I am trying to extract an array of objects from another JSON array, which is received through an HTTP request in Angular 5. My goal is to display the values in the console. I have successfully made the HTTP request and subscribed to the service.
When using *ngFor in the template, everything works fine. However, when I try to access it directly in the Typescript file, the value appears as undefined in the console.
This is how my JSON data looks:
{"data":[
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
},
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
},
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
}]
}
While I can access the data using ngFor in the HTML file and retrieve the values, accessing it in Typescript with console.log(this.obj[data]) results in undefined being displayed.
I need to create a new array that only includes the id and title fields in Angular 5. Any assistance on this matter would be greatly appreciated.
Here is my Service page:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from'@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class ConfigService {
private URL: string = 'some URL';
constructor(private http:HttpClient) {}
getData(): Observable<any> {
return this.http.get(this.URL+ '/getdata', {responseType: 'json'});
}
}
And this is my component:
import { Component, OnInit, Input } from '@angular/core';
import { ConfigService } from '../services/config.service';
import { FormControl } from '@angular/forms';
import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { Observable, BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class childComponent implements OnInit {
allData: any = [];
getALLData() {
this.config.getData().subscribe(
data => { this.allData= data['data']},
err => console.error(err),
() => console.log('done loading data')
);
}
ngOnInit() {
this.getALLData();
console.log(this.allData); // In this case, the console shows 'undefined'
}
}
If you have any suggestions or solutions, please let me know. Thank you!