Issue
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
The HTTP service returns a response object which contains the data.
const request = this.http.get('...');
// The subscribe triggers the HTTP request, and you can call
// subscribe again on the same variable to trigger another HTTP request
request.subscribe((resp)=>{
// this will show the response object.
console.log(resp);
});
You should call either take
or first
to ensure that the HTTP request is completed.
request.first().subscribe((resp)=>{
// there are no memory leaks now
});
You should handle errors.
request
.first()
.catch((err,o)=>console.error(err))
.subscribe((resp)=>{
// called if only successful
});
When the HTTP request is a success you can map the response to the actual data from the server.
request
.first()
.catch((err,o)=>console.error(err))
.map((resp)=>resp.data)
.subscribe((data)=>{
// this will be the JSON from the server
console.log(data);
});
This is how I would write the HTTP service function.
getFoods() {
return this.http
.get('....')
.first()
.catch((err,o)=>console.error('There was an error'))
.map((resp)=>resp.data);
}
Later in your component. You need to log the response data only after the observable has finished.
this.data = null;
console.log('data is null', this.data);
this.server.getFoods().subscribe((data)=>{
this.data = data;
console.log('data is now set', this.data);
});
console.log('data is still null', this.data);
I think this answers your question as the data is lazy loaded after the HTTP request is completed.
Answered By - Reactgular
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.