'Retrive array of object from json array of object though http request typescript angular 5
I want to retrieve array of object from another JSON array of object, which I am getting through HTTP request in angular 5 and want to display the values in console.Here I can successfully call the HTTP request and able to subscribe the service.
When parsing through *ngFor in template its working fine, but when I am directly accessing in typescript file, its showing undefined value in console.
My JSON like this.
{"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'
}]
}
I can access it though ngFor in html file, its giving the value, but when I am accessing in typescript like console.log(this.obj[data]); its showing undefined.
I need to create a new array which having only id and title field in angular 5 Kindly help. 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'});
}
}
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); //here its showing undefined in console
}
}
Kindly help on this
Solution 1:[1]
This is answer was helpful for retrieving json array data from api to angular.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vijay Kumar |