How do i handle JSON Data in Angular 2?

Hi I am new to Angular and I have been trying to learn Angular 2 so be gentle :).
I have been trying to use WordPress as my data API using WP API plugin. And have so far been able to get posts from WordPress. And below is my code for the data service.

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=>res.json())
            //.do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }

    //todo fix search

    getPost(filterid:number):Observable<any[]>{
         //filterid is the id of a specific post
        this._dataURL = this._dataURL + '/' + filterid;
        return this.http.get(this._dataURL)
            .map(res => res.json())
            .catch(this.handleError);
    }




    private handleError (error: Response) {

        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

}

In the code I get all the post data using the getPosts() method but I also have a getPost() method to fetch specific post.
I was wondering if I could use the JSON data fetched by getPosts() and use it again in getPost() method. Currently what the getPost() does is call the http.get again I do not want to make http.get request again and again.

Read More

I want the getPosts() to make one request, fetch the data and store is somewhere so that other methods can use the data and do their specific manipulations.

Thanks

Related posts

2 comments

  1. 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
             })
        }
    
  2. 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.

Comments are closed.