In my Ionic 3 project, I am sending an API request and displaying the response on a page called Home.ts by using a Provider. I want to ensure that the data remains in the provider after the initial request so that all pages utilizing this Provider can access the same information without needing to make another API call. What would be the most effective approach to achieve this?
Versions: ionic CLI: 3.10; Ionic Framework: 3.7.1
people-service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PeopleServiceProvider {
requisicao: any;
films: Observable<any>;
//getApiUrl : string = "https://jsonplaceholder.typicode.com/posts";
getApiUrl : string = "https://randomuser.me/api/?results=3";
constructor(public http: Http) {
this.requisicao = null;
}
// returns a Observable
getHTTP(docache: boolean) {
return this.http.get(this.getApiUrl)
.do(res => console.log(res.json()))
.map(res => res.json());
}
}
Home.ts:
import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import {PeopleServiceProvider} from '../../providers/people-service/people-service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [PeopleServiceProvider]
})
export class HomePage {
films: Observable<any>;
public people: any;
req: any;
constructor(public navCtrl: NavController, public loading: LoadingController, public peopleService: PeopleServiceProvider) {
this.people = null;
}
loadPeople(docache:boolean) {
let loader = this.loading.create({
content: 'Wait...',
});
loader.present().then(() => {
this.req = this.peopleService.getHTTP(docache);
this.req.subscribe((data)=>{
this.people = data.results;
console.log(this.people);
});
// this.peopleService.getPosts(docache);
loader.dismiss();
});
}
}
Home.html
<button ion-button secondary (click)='loadPeople(true);'>Do cache</button>