I create a news application by getting data from my JSON API and I would simply like to store my data in Ionic's storage and display what's in storage when the user no longer has an internet connection.
Currently, I retrieve my data with the HttpClient and return an Observable .
I can store them in the storage and display it. But I'm not sure that my life cycle is working properly and I don't know if what I did is good.
ArticleService :
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/map';
import {Platform} from "ionic-angular";
import {ArticleCard} from "../classes/ArticleCard";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import {IArticleCard} from "../interfaces/IArticleCard";
@Injectable()
export class ArticlesService {
urlArticlesCards: string = "https://mylink";
constructor(private http: HttpClient, public platform: Platform) {
}
getAlaUneCards(): Observable<IArticleCard[]> {
return this.http.get<any>(this.urlArticlesCards)
.map(res => {
return res.map(article => {
return new ArticleCard(
article.id,
article.image,
article.titre,
);
});
});
}
}
Interface :
export interface IArticleCard {
results: {
id: number;
image: string;
titre: string;
}[]
}
ArticleCard :
export class ArticleCard {
id: number;
image: string;
titre: string;
constructor(id: number, image: string, titre: string) {
this.id = id;
this.image = image;
this.titre = titre;
}
}
Home :
observable$: Observable<IArticleCard[]>;
tabCards: Array<Object>= [];
constructor(public navCtrl: NavController, private articleService: ArticlesService, private storage: Storage) {}
ionViewWillEnter() {
this.observable$ = this.articleService.getAlaUneCards();
this.observable$.subscribe(cards => {
if(cards){
this.storage.set('alaune_cards', cards);
}
this.storage.get('alaune_cards').then((card) => {
this.tabCards = card;
})
});
}