I've been struggling with the following: I have an angular-based ionic app and I`m struggling to cache the results for offline use. I don't (necessarily) need the online/offline check as I think I can manage that on my own.
Injectable/Post provider
import { Http, Headers, RequestOptions } from "@angular/http";
import "rxjs/add/operator/map";
//import {Observable,of, from } from 'rxjs';
@Injectable()
export class PostProvider {
//private records$: Observable<Record[]>;
server: string = "https://server/api_endpoint/";
constructor(public http: Http) {}
postData(body, file) {
let type = "application/json; charset=UTF-8";
let headers = new Headers({ "Content-Type": type });
let options = new RequestOptions({ headers: headers });
return this.http
.post(this.server + file, JSON.stringify(body), options)
.map(res => res.json());
}
}
Component
In the component, I'm using the aksi for CRUD instructions towards the API
loadCustomer() {
return new Promise(resolve => {
let body = {
aksi: "getdata",
user: this.username
};
this.postPvdr.postData(body, "proses-api.php").subscribe(
data => {
for (let customer of data.result) {
//this.customers.push(customer);
this.logn = customer.nume;
this.logn = customer.pret;
this.comis = customer.comis +' %';
this.rhg = customer.rhg;
this.pdg = customer.pdg;
this.ptg = customer.ptg;
this.defaultList.push(customer);
}
//defaultList is used to serve up the data into an autocomplete field
this.completeTestService.customerList = this.defaultList;
resolve(true);
},
);
});
}
I'm ultranew to angular so I've barely understood the concept of Observables from quickreads. I've tried building it with $cacheFactory, got overwhelmed. Followed a video on how to do it but it ended up being for previous angular versions. Stumbled upon this
And when I tried to implement it got
Generic type 'Record' requires 2 type argument(s)
If the code takes too much to write, any example of how this should work or (clear) documentation would be a blessing. After spending hours on this I'm at a point where I just feel stupid.
The Angular docs provide some examples on how to cache http requests using an interceptor. There is no provided caching service, so you will need to create your own service for this.
Below is one of their snippets on how to cache http requests in Angular.
Make sure to provide the interceptor in the module you plan to use it in.