How do i handle JSON Data in Angular 2?
Yes you can firstly fetch your all data and save into one variable or another methods is where you subscribing your data perform for loop
and match with your filterId
where the process matches store that data into array and implement your manipulation according to need. here is example assuming your data is in array form..
import {Injectable} from "angular2/core";import {Http, Response} from 'angular2/http';import {Observable} from 'rxjs/Rx';import {PostInterface} from './data.interface';import {Headers} from "angular2/http";import {RequestOptions} from "angular2/http";@Injectable()export class DataService{ private _dataURL : string = 'http://localhost/wordpress/?rest_route=/wp/v2/posts'; posts : PostInterface []; post : PostInterface; errorMessage : string; constructor(private http:Http){} getPosts():Observable<any[]>{ //return this.http.get(this._dataURL).map((res:Response) => res.json()); return this.http.get(this._dataURL) .map(res=>{ if(res.json()){ return res.json() } }); //.do(data => console.log(data)) // eyeball results in the console .catch(this.handleError); } // Method in any file where you want to subscribe your data and wanna fetch specific post // singlePost: Array<any>= []; methodName(filterid:number){ service.getPosts() .subscribe(res=>{ console.log(res) // Here you data whihc is coming from .map i.e getPosts methods using Http for(let i=0; i< res.length ; i++){ // I am asuming your data is in array from so performing length functionality if(filterid == res[i].filterid){ this.singlePost = res[i]; break; } } console.log(this.singlePost) // This will return your single Specific POst without using `Http` again and again }) }
You could try something like that using the do
operator to save the data into your service when the getPosts
result is received:
@Injectable()export class DataService{ private _dataURL : string = 'http://localhost/wordpress/?rest_route=/wp/v2/posts'; posts : PostInterface []; post : PostInterface; errorMessage : string; constructor(private http:Http){} getPosts():Observable<any[]>{ //return this.http.get(this._dataURL).map((res:Response) => res.json()); return this.http.get(this._dataURL) .map(res=>res.json()) .do(data => this.posts = data) // <-------- .catch(this.handleError); } findPostById(id) { if (this.posts != null) { return this.posts.find(((element, index, array) { return (element.id = id); }); } else { return null; } } getPost(filterid:number):Observable<any[]>{ var post = findPostById(filterid); if (post != null) { // <-------- return post; } else { this._dataURL = this._dataURL + '/' + filterid; return this.http.get(this._dataURL) .map(res => res.json()) .catch(this.handleError); } }
Feel free to adapt this code to your needs.