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.
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
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 yourfilterId
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..You could try something like that using the
do
operator to save the data into your service when thegetPosts
result is received:Feel free to adapt this code to your needs.